I have my JPA Entity class, AssetOrder. And I have defined a custom JSONSerializer for another entity called Product, which is used by AssetOrder entity internally to map the productID from the Product. As we can see the AssetOrder also has a JSONSerializer for formatting the Date objects.
The Date object JSON serialization works perfectly. However, I am not sure whether the JSONSerializer for the Product works perfectly. When I retrieve the AssetOrder objects from the JPA DAO and try to display on my client page, I get a response saying - Response contains invalid JSON data. I have enclosed the three java classes, AssetOrder.java, Product.java and JSONProductSerializer.java.
Please help, where I have done wrong.
Thanks.
//===================== AssetOrder.java ============================
package my.pkg;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
#JsonAutoDetect
#Entity
public class AssetOrder {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long orderId;
private String orderRequesterSignum;
private String orderOwnerSignum;
#JoinColumn(name = "productID")
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Product product;
//private String productId;
private int duartion;
private String processInstanceUUID;
private Date orderDate;
private Date orderDeliveryDate;
private Date modifiedDate;
private String status;
private String comments;
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public String getOrderRequesterSignum() {
return orderRequesterSignum;
}
public void setOrderRequesterSignum(String orderRequesterSignum) {
this.orderRequesterSignum = orderRequesterSignum;
}
public String getOrderOwnerSignum() {
return orderOwnerSignum;
}
public void setOrderOwnerSignum(String orderOwnerSignum) {
this.orderOwnerSignum = orderOwnerSignum;
}
public int getDuartion() {
return duartion;
}
public void setDuartion(int duartion) {
this.duartion = duartion;
}
public String getProcessInstanceUUID() {
return processInstanceUUID;
}
public void setProcessInstanceUUID(String processInstanceUUID) {
this.processInstanceUUID = processInstanceUUID;
}
#JsonSerialize(using=JsonDateSerializer.class)
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
#JsonSerialize(using=JsonDateSerializer.class)
public Date getOrderDeliveryDate() {
return orderDeliveryDate;
}
public void setOrderDeliveryDate(Date orderDeliveryDate) {
this.orderDeliveryDate = orderDeliveryDate;
}
#JsonSerialize(using=JsonDateSerializer.class)
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Date modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
#JsonSerialize(using=JsonProductSerializer.class)
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
}
//============================Product.java=========================
package my.pkg;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long productID;
private String productName;
private String productCategory;
private String productDesc;
private Long productOwnerId;
private Long productHierarchyId;
private String productProcessID;
private Long productGroupID;
public Long getProductID() {
return productID;
}
public void setProductID(Long productID) {
this.productID = productID;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCategory() {
return productCategory;
}
public void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
public String getProductDesc() {
return productDesc;
}
public void setProductDesc(String productDesc) {
this.productDesc = productDesc;
}
public Long getProductOwnerId() {
return productOwnerId;
}
public void setProductOwnerId(Long productOwnerId) {
this.productOwnerId = productOwnerId;
}
public Long getProductHierarchyId() {
return productHierarchyId;
}
public void setProductHierarchyId(Long productHierarchyId) {
this.productHierarchyId = productHierarchyId;
}
public String getProductProcessID() {
return productProcessID;
}
public void setProductProcessID(String productProcessID) {
this.productProcessID = productProcessID;
}
public Long getProductGroupID() {
return productGroupID;
}
public void setProductGroupID(Long productGroupID) {
this.productGroupID = productGroupID;
}
}
//=================JSONProductSerializer.java=========================
//the commented part in the below code didn't work either
//=====================================================================
package my.pkg;
import java.io.IOException;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* Used to serialize com.xxxx.persistence.entity.Product, which is not a common JSON
* type, so we have to create a custom serialize method;.
*
* source: google.com
*/
#Component
public class JsonProductSerializer extends JsonSerializer<Product>{
#Override
public void serialize(Product product, JsonGenerator gen, SerializerProvider provider)
throws IOException, JsonProcessingException {
synchronized(product) {
/*gen.writeStartObject();
gen.writeNumberField("productID", product.getProductID());
gen.writeStringField("productName", product.getProductName());
gen.writeStringField("productCategory", product.getProductCategory());
gen.writeStringField("productDesc", product.getProductDesc());
gen.writeNumberField("productOwnerId", product.getProductOwnerId());
gen.writeNumberField("productHierarchyId", product.getProductHierarchyId());
gen.writeStringField("productProcessID", product.getProductProcessID());
gen.writeNumberField("productGroupID", product.getProductGroupID());
gen.writeEndObject();*/
gen.writeNumber(product.getProductID());
gen.writeString(product.getProductName());
gen.writeString(product.getProductCategory());
gen.writeString(product.getProductDesc());
gen.writeNumber(product.getProductOwnerId());
gen.writeNumber(product.getProductHierarchyId());
gen.writeString(product.getProductProcessID());
gen.writeNumber(product.getProductGroupID());
}
}
}
Actually, the problem turned out to be with the java.util.Date serialization with com.fasterxml.jackson (latest version of jackson) package. I reverted to org.codehaus.jackson and everything works like a charm.
Related
Good morning I have a small query, I am doing a small web service rest with spring boot, the issue is that it is working fine and everything else, as I am doing as follows, receives a parameter and returns a response based on a Stored Procedue in the database:
But now I have changed the request, and it is including header and body, like the following:
{
"ValidateClient": {
"Header": {
"country": "VE",
"lang": "ES",
"entity": "TMVE",
"system": "76",
"subsystem": "APP",
"operation": "ValidateClient",
"timestamp": "2019-10-23T08:48:08.474Z",
"msgType": "REQUEST"
},
"Body": {
"validateClientRequest": {
"movil": "04141734272"
}
}
}
}
Which when executing it gives me an answer of not found the mobile, it is a default response when it cannot read the mobile parameter or it is sent empty
My Code
Main Class
package com.app.validate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ValidateClientApp {
public static void main(String[] args) {
SpringApplication.run(ValidateClientApp.class, args);
}
}
Controller
package com.app.validate.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.app.validate.dao.ValidateClientAppRepository;
import com.app.validate.entity.DriverBonificados;
import com.app.validate.entity.ResponseVo;
#RestController
public class ValidateClientAppController {
#Autowired
private ValidateClientAppRepository dao;
#PostMapping(value = "/ValidateClientApp",consumes = "application/json",produces="application/json")
public ResponseVo ValidateClient(#RequestBody DriverBonificados driver) {
//System.out.println(driver.getMovil());
return dao.validarClienteBonifiado(driver.getMovil());
}
}
Dao
package com.app.validate.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.app.validate.entity.DriverBonificados;
import com.app.validate.entity.ResponseVo;
#Repository
public interface ValidateClientAppRepository extends JpaRepository<DriverBonificados, Integer> {
#Query(nativeQuery = true,value = "call ValidacionClienteBonificado(:movil)")
ResponseVo validarClienteBonifiado(#Param("movil") String pMovil);
}
Entity
package com.app.validate.entity;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="DriverBonificados")
public class DriverBonificados {
#Id
private int id;
private String movil;
private String contador;
private Date fecha_driver;
private Date fecha_alta;
private Date fecha_fin;
private Date codigo_transaccion;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMovil() {
return movil;
}
public void setMovil(String movil) {
this.movil = movil;
}
public String getContador() {
return contador;
}
public void setContador(String contador) {
this.contador = contador;
}
public Date getFecha_driver() {
return fecha_driver;
}
public void setFecha_driver(Date fecha_driver) {
this.fecha_driver = fecha_driver;
}
public Date getFecha_alta() {
return fecha_alta;
}
public void setFecha_alta(Date fecha_alta) {
this.fecha_alta = fecha_alta;
}
public Date getFecha_fin() {
return fecha_fin;
}
public void setFecha_fin(Date fecha_fin) {
this.fecha_fin = fecha_fin;
}
public Date getCodigo_transaccion() {
return codigo_transaccion;
}
public void setCodigo_transaccion(Date codigo_transaccion) {
this.codigo_transaccion = codigo_transaccion;
}
}
Interface Response Stored Procedue
package com.app.validate.entity;
public interface ResponseVo {
String getCode();
String getResult();
}
How could you do to read the Json with header and body? I'm new to spring boot
UPDATE
According to what Silverfang said, I created the classes said by him, but I get an error that I describe next:
BodyRequest.java
public class BodyRequest {
private String validateClientRequest;
private String movil;
public String getValidateClientRequest() {
return validateClientRequest;
}
public void setValidateClientRequest(String validateClientRequest) {
this.validateClientRequest = validateClientRequest;
}
public String getMovil() {
return movil;
}
public void setMovil(String movil) {
this.movil = movil;
}
}
HeaderRequest.java
package com.app.validate.controller;
import java.util.Date;
public class HeaderRequest {
private String country;
private String lang;
private String entity;
private String system;
private String subsystem;
private String operation;
private Date timestamp;
private String msgType;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getEntity() {
return entity;
}
public void setEntity(String entity) {
this.entity = entity;
}
public String getSystem() {
return system;
}
public void setSystem(String system) {
this.system = system;
}
public String getSubsystem() {
return subsystem;
}
public void setSubsystem(String subsystem) {
this.subsystem = subsystem;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType;
}
}
RequestBodyDemo.java
package com.app.validate.controller;
public class RequestBodyDemo {
private ValidateClientRequest ValidateClient;
public ValidateClientRequest getValidateClient() {
return ValidateClient;
}
public void setValidateClient(ValidateClientRequest validateClient) {
ValidateClient = validateClient;
}
}
ValidateClientRequest
package com.app.validate.controller;
public class ValidateClientRequest {
private BodyRequest Body;
private HeaderRequest Header;
public BodyRequest getBody() {
return Body;
}
public void setBody(BodyRequest body) {
Body = body;
}
public HeaderRequest getHeader() {
return Header;
}
public void setHeader(HeaderRequest header) {
Header = header;
}
}
My Controller (Update)
package com.app.validate.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.app.validate.dao.ValidateClientAppRepository;
import com.app.validate.entity.DriverBonificados;
import com.app.validate.entity.ResponseVo;
#RestController
public class ValidateClientAppController {
#Autowired
private ValidateClientAppRepository dao;
#PostMapping(value = "/ValidateClientApp",consumes = "application/json",produces="application/json")
public ResponseVo ValidateClient(#RequestBody RequestBodyDemo req) {
System.out.println(req.getValidateClient().getBody().getMovil());
return dao.validarClienteBonifiado(req.getValidateClient().getBody().getMovil());
}
}
The error I get:
From what I understand you have changed the request format and now want the same request body to work for the same controller.
I think you were trying to add the fields to the header. What you are doing here is not the right way to do it. It should goes to header section rather than in the body section of the Postman app. But doing so, you will have to specify these header separately as these are custom headers which will be a lot of work.
Answer to your question
Going by what you were trying to do. Since now you have changed the request body. You will have to make changes in the controller class too. Now it will require three classes If you want to do it in a modular way.
The first class will be BodyRequest.java
private string validateClientRequest;
private string movil;
The next class will be HeaderRequest.java
private string country;
private string lang;
private string entity;
private string system;
private string subsystem;
private string operation;
private Date timestamp;
private string msgType;
Next class will be ValidateClientRequest.java
private HeaderRequest Header;
private BodyRequest Body;
Now for the RequestBodyDemo class;
private ValidateClientRequest ValidateClient;
Note : Use appropriate Getter and setter along with #JsonProperty if you are masking the input request data.
Once these things are done. In your controller Instead of using Entity in #RequestBody Use the class RequestBodyDemo. Once that is done. Just try printing the values just to check whether you are getting them right or not. Then use getter for fetching any value that you need.
Edit :
public ResponseVo ValidateClient(#RequestBody RequestBodyDemo req) {
System.out.println(req.getValidateClient().getBodyrequest().getMovil());
return dao.validarClienteBonifiado(req.getValidateClient().getBodyrequest().getMovil());
}
Note : Use appropriate getter method here.
I've got the following task:
I need to Produce a Spring Boot REST API that reads in data from a JSON file and allows the user to filter by colour.
The URL should look similar to: http://localhost:8080/cars?colour=red
The input data is in the included JSON file (cars.json)
It is of the form:
{
"cars": [
{
"brand": "ford",
"model": "fiesta",
"fuel": "petrol",
"doors": 5,
"colour": "blue"
}
]
}
I'm struggling to structurize JSON parsing classes properly, and here's my code
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.challenge.esure.domain.Cars;
import com.challenge.esure.exceptions.ColourNotFoundException;
import com.challenge.esure.service.MainService;
#RestController
public class MainController {
private final MainService mainService;
#Autowired
public MainController(MainService mainService) {
this.mainService = mainService;
}
#GetMapping("/all")
public List<Cars> getAll() throws IOException {
return mainService.getAllRecords();
}
#GetMapping("/cars?colour={colour}")
public Cars getColour(#PathVariable("colour") String colour) throws IOException, ColourNotFoundException {
return mainService.getCarColour(colour);
}
}
//Service:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import com.challenge.esure.domain.CarDetails;
import com.challenge.esure.domain.Cars;
import com.challenge.esure.exceptions.ColourNotFoundException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
#Service
public class MainService {
public List<Cars> getData() throws IOException{
Resource resource = new ClassPathResource("cars.json");
InputStream input = resource.getInputStream();
File file = resource.getFile();
ObjectMapper objectMapper = new ObjectMapper();
List<Cars> car = Arrays.asList(objectMapper.readValue(file, Cars[].class));
return car.stream().collect(Collectors.toList());
}
public List<Cars> getAllRecords() throws IOException {
return getData();
}
public Cars getCarColour(String colour) throws ColourNotFoundException, IOException {
return getData().stream()
.filter(Cars -> Cars.getColour().equals(colour))
.findAny()
.orElseThrow(() -> new ColourNotFoundException("We don't have cars with that colour"));
}
}
// Domain
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Cars {
private ArrayList<Object> cars;
private String brand;
private String model;
private String fuel;
private Integer doors;
private String colour;
public Cars() {
}
public Cars(ArrayList<Object> cars, String brand, String model, String fuel, Integer doors, String colour) {
this.cars = cars;
this.brand = brand;
this.model = model;
this.fuel = fuel;
this.doors = doors;
this.colour = colour;
}
public ArrayList<Object> getCars() {
return cars;
}
public void setCars(ArrayList<Object> cars) {
this.cars = cars;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getFuel() {
return fuel;
}
public void setFuel(String fuel) {
this.fuel = fuel;
}
public Integer getDoors() {
return doors;
}
public void setDoors(Integer doors) {
this.doors = doors;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
}
//Exception
public class ColourNotFoundException extends Exception {
public ColourNotFoundException(String what) {
super(what);
}
}
You can use the below data structure
#JsonIgnoreProperties(ignoreUnknown = true)
public class CarResponse {
List<Car> cars;
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
#Override
public String toString() {
return "CarResponse{" +
"cars=" + cars +
'}';
}
}
public class Car {
private String brand;
private String model;
private String fuel;
private Integer doors;
private String colour;
}
CarResponse carResponse= objectMapper.readValue(jsonString, CarResponse.class);
I have converted the JSON into POJO using GSON.
I am looking to store Employee entity object into mysql using JPA's save() method. But I am getting an error saying "cannot determine the type for Address". So how should I go with this?
Here is the error:
Could not determine type for : Address
Employee.java
package com.example.demo;
import java.math.BigDecimal;
import java.util.Map;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.google.gson.annotations.Expose;
#Entity
public class Employee {
#Id
private int id;
private String name;
private int age;
private BigDecimal salary;
private String designation;
private Address address;
private long[] phoneNumbers;
/*Getter and Setter Methods*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public long[] getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(long[] phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address.java
package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.Id;
//#Entity
public class Address {
#Id
private String street;
private String city;
private int zipCode;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getZipCode() {
return zipCode;
}
public void setZipcode(int zipcode) {
this.zipCode = zipcode;
}
#Override
public String toString(){
return getStreet() + ", "+getCity()+", "+getZipCode();
}
}
Controller Class
package com.example.demo;
import net.sf.json.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import net.sf.json.JSONObject;
#Controller // This means that this class is a Controller
#RequestMapping(path="/demo") // This means URL's start with /demo
(after Application path)
public class MainController {
#Autowired // This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it
to handle the data
private UserRepository userRepository;
#GetMapping(path="/add") // Map ONLY GET Requests
public #ResponseBody String addNewUser (#RequestBody String json) {
// #ResponseBody means the returned String is the response, not a view name
// #RequestParam means it is a parameter from the GET or POST request
//JSONObject jsonObject = JSONObject.fromObject(json);
Gson gson=new GsonBuilder().create();
Employee employee =gson.fromJson(json,Employee.class);
userRepository.save(employee);
return "Successfully added to database using JPA!";
}
#GetMapping(path="/all")
public #ResponseBody Iterable<Employee> getAllUsers() {
// This returns a JSON or XML with the users
return userRepository.findAll();
}
}
Try adding implements Serializable for your Entity classes.
ie.
#Entity
public class Employee implements Serializable{
}
Whenever you use #Entity annotation in your class and trying to save its instance in database. At very intially a create table command is formed in hibernate which creates table in the database with the given specifications. As in employee table you specify the datatypes of all data-members. When cursor come to 'Address', it gave error because hibernate not able to find any datatype related this or any table related this.
As you commented #Entity annoatation in Address class. So no table regarding that will be created in database.
Address is class reference for this hibernate need the class(table). As class(table) is not there ,so the error comes.
i have i a class StudentAdmissinAssoDTO that have Other class references
as below
StudentAdmissinAssoDTO
package com.rasvek.cg.entity;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonBackReference;
public class StudentAdmissinAssoDTO
{
private PrimaryStudentAdmission primaryAdmission;
private StudentDetails studentDetailsDto;
private StudentJoiningDetails studentJoiningDetails;
private StudentPresentClassDetails studentPresentClassDetails;
private StudentGeneralDetails studentGeneralDetails;
private StudentPrevSchoolDetails studentPrevSchoolDetails;
private StudentParentDetails studentParentDetails;
private MasterAddress masterAddress;
private List<AssocFeeStudent> assocFeeStudentId;
public StudentDetails getStudentDetailsDto() {
return studentDetailsDto;
}
public void ListStudentDetailsDto(StudentDetails studentDetailsDto) {
this.studentDetailsDto = studentDetailsDto;
}
public PrimaryStudentAdmission getPrimaryAdmission() {
return primaryAdmission;
}
public void ListPrimaryAdmission(PrimaryStudentAdmission primaryAdmission) {
this.primaryAdmission = primaryAdmission;
}
public StudentJoiningDetails getStudentJoiningDetails() {
return studentJoiningDetails;
}
public void ListStudentJoiningDetails(StudentJoiningDetails studentJoiningDetails) {
this.studentJoiningDetails = studentJoiningDetails;
}
public StudentPresentClassDetails getStudentPresentClassDetails() {
return studentPresentClassDetails;
}
public void ListStudentPresentClassDetails(StudentPresentClassDetails studentPresentClassDetails) {
this.studentPresentClassDetails = studentPresentClassDetails;
}
public StudentGeneralDetails getStudentGeneralDetails() {
return studentGeneralDetails;
}
public void ListStudentGeneralDetails(StudentGeneralDetails studentGeneralDetails) {
this.studentGeneralDetails = studentGeneralDetails;
}
public StudentPrevSchoolDetails getStudentPrevSchoolDetails() {
return studentPrevSchoolDetails;
}
public void ListStudentPrevSchoolDetails(StudentPrevSchoolDetails studentPrevSchoolDetails) {
this.studentPrevSchoolDetails = studentPrevSchoolDetails;
}
public StudentParentDetails getStudentParentDetails() {
return studentParentDetails;
}
public void ListStudentParentDetails(StudentParentDetails studentParentDetails) {
this.studentParentDetails = studentParentDetails;
}
public MasterAddress getMasterAddress() {
return masterAddress;
}
public void ListMasterAddress(MasterAddress masterAddress) {
this.masterAddress = masterAddress;
}
public List<AssocFeeStudent> getAssocFeeStudentId() {
return assocFeeStudentId;
}
public void ListAssocFeeStudentId(List<AssocFeeStudent> assocFeeStudentId) {
this.assocFeeStudentId = assocFeeStudentId;
}
}
and i am getting this Exception
(http-nio-8017-exec-3:org.springframework.http.converter.json.MappingJackson2HttpMessageConverter):
[org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.logWarningIfNecessary(AbstractJackson2HttpMessageConverter.java:205)]
Failed to evaluate Jackson deserialization for type [[simple type, class com.rasvek.cg.entity.StudentAdmissinAssoDTO]]: java.lang.IllegalArgumentException: Can not handle managed/back reference 'defaultReference': no back reference property found from type [collection type; class java.util.Set, contains [simple type, class com.rasvek.cg.entity.MasterAddress]]
please look at MasterAddress
package com.rasvek.cg.entity;
//Generated May 14, 2018 11:39:07 PM by Hibernate Tools 5.1.7.Final
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
/**
* MasterAddress generated by hbm2java
*/
#Entity
#Table(name = "master_address", catalog = "campus_guru_01")
#JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class,property = "addressId")
public class MasterAddress implements java.io.Serializable {
private Integer addressId;
private Integer studentAdmissionId;
private String isSame;
private MasterAddressCountry masterAddressCountry;
private MasterAddressDistrict masterAddressDistrict;
private MasterAddressState masterAddressState;
private String houseNum;
private String streetAddress;
private String citymandal;
private String pincode;
private String addressType;
private Set<AssocStaffAddress> assocStaffAddresses = new HashSet<AssocStaffAddress>(0);
private Set<AssocStudentAddress> assocStudentAddresses = new HashSet<AssocStudentAddress>(0);
public MasterAddress() {
}
public MasterAddress(MasterAddressCountry masterAddressCountry, MasterAddressDistrict masterAddressDistrict,
MasterAddressState masterAddressState) {
this.masterAddressCountry = masterAddressCountry;
this.masterAddressDistrict = masterAddressDistrict;
this.masterAddressState = masterAddressState;
}
public MasterAddress(MasterAddressCountry masterAddressCountry, MasterAddressDistrict masterAddressDistrict, MasterAddressState masterAddressState, String houseNum, String streetAddress, String citymandal, String pincode, String addressType, Set<AssocStaffAddress> assocStaffAddresses, Set<AssocStudentAddress> assocStudentAddresses) {
this.masterAddressCountry = masterAddressCountry;
this.masterAddressDistrict = masterAddressDistrict;
this.masterAddressState = masterAddressState;
this.houseNum = houseNum;
this.streetAddress = streetAddress;
this.citymandal = citymandal;
this.pincode = pincode;
this.addressType = addressType;
this.assocStaffAddresses = assocStaffAddresses;
this.assocStudentAddresses = assocStudentAddresses;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "address_id", unique = true, nullable = false)
public Integer getAddressId() {
return this.addressId;
}
public void setAddressId(Integer addressId) {
this.addressId = addressId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "country_id", nullable = false)
public MasterAddressCountry getMasterAddressCountry() {
return this.masterAddressCountry;
}
public void setMasterAddressCountry(MasterAddressCountry masterAddressCountry) {
this.masterAddressCountry = masterAddressCountry;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "district_id", nullable = false)
public MasterAddressDistrict getMasterAddressDistrict() {
return this.masterAddressDistrict;
}
public void setMasterAddressDistrict(MasterAddressDistrict masterAddressDistrict) {
this.masterAddressDistrict = masterAddressDistrict;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "state_id", nullable = false)
public MasterAddressState getMasterAddressState() {
return this.masterAddressState;
}
public void setMasterAddressState(MasterAddressState masterAddressState) {
this.masterAddressState = masterAddressState;
}
#Column(name = "house_num", length = 45)
public String getHouseNum() {
return this.houseNum;
}
public void setHouseNum(String houseNum) {
this.houseNum = houseNum;
}
#Column(name = "street_address", length = 45)
public String getStreetAddress() {
return this.streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
#Column(name="citymandal")
public String getCitymandal() {
return this.citymandal;
}
public void setCitymandal(String citymandal) {
this.citymandal = citymandal;
}
#Column(name = "pincode", length = 45)
public String getPincode() {
return this.pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
#Column(name = "address_type", length = 9)
public String getAddressType() {
return this.addressType;
}
public void setAddressType(String addressType) {
this.addressType = addressType;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "masterAddress")
public Set<AssocStaffAddress> getAssocStaffAddresses() {
return this.assocStaffAddresses;
}
public void setAssocStaffAddresses(Set<AssocStaffAddress> assocStaffAddresses) {
this.assocStaffAddresses = assocStaffAddresses;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "masterAddress")
public Set<AssocStudentAddress> getAssocStudentAddresses() {
return this.assocStudentAddresses;
}
public void setAssocStudentAddresses(Set<AssocStudentAddress> assocStudentAddresses) {
this.assocStudentAddresses = assocStudentAddresses;
}
#Column(name="student_admission_id")
public Integer getStudentAdmissionId() {
return studentAdmissionId;
}
public void setStudentAdmissionId(Integer studentAdmissionId) {
this.studentAdmissionId = studentAdmissionId;
}
#Column(name="is_same")
public String getIsSame() {
return isSame;
}
public void setIsSame(String isSame) {
this.isSame = isSame;
}
}
there is no dependency Dependency Between StudentAdmissinAssoDTO and MasterAddress .
i am just using StudentAdmissinAssoDTO to make nested json objects .
so that i can get them in the controller
like bellow
MasterAddress masterAddress =null;
masterAddress = studentAdmissinAssoDTO.getMasterAddress();
why i am getting this Exception
(http-nio-8017-exec-3:org.springframework.http.converter.json.MappingJackson2HttpMessageConverter): [org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.logWarningIfNecessary(AbstractJackson2HttpMessageConverter.java:205)]
Failed to evaluate Jackson deserialization for type [[simple type, class com.rasvek.cg.entity.StudentAdmissinAssoDTO]]: java.lang.IllegalArgumentException: Can not handle managed/back reference 'defaultReference': no back reference property found from type [collection type; class java.util.Set, contains [simple type, class com.rasvek.cg.entity.MasterAddress]
can any one Explain why its happening so. thank you!.
i found my mistake there was i misplace of #JsonManagedReference in MasterDistrict Class of MasterAddress
I have an application where users have to save informations to DataBase and images to file System directory and save the path of images in Database. My question is how to get the ID (auto increment) from the Database Table to make a path in the database. Exemple: car1200.jpeg (car: image name , 1200: Id of the user).
here my code :
Controller :
#RequestMapping(value="/save",method=RequestMethod.POST)
public String add ( #RequestParam("prix") Long prix,
RequestParam("adresse") String ville,
#RequestParam("categorie") String categorie,
#RequestParam("photos") MultipartFile file,
) throws FileNotFoundException
{
String chemin=null;
if (!file.isEmpty())
{
try {
String orgName = file.getOriginalFilename();
// this line to retreive just file name
String
name=orgName.substring(orgName.lastIndexOf("\\")+1,orgName.length());
chemin="e:\\images\\"+name;// here I want to add ID of the user ,I
//don t know how to get since it is auto increment
File file1=new File(chemin);
file.transferTo(file1);
} catch (IOException e) {
e.printStackTrace();
}
}
annonce.setImage(chemin);
annonce.setTitre(prix);
annonce.setCorps(ville);
annonce.setPrix(cetegorie)
annoncedao.save(annonce);
return "SuccessAddAnnonce";
}
Annonce class:
package com.eBenamar.Entities;
import java.io.Serializable;
import java.sql.Blob;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.OneToOne;
import org.hibernate.annotations.Cascade;
import org.hibernate.validator.constraints.NotEmpty;
/**
* #author user
*
*/
#Entity
public class Annonce implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id #GeneratedValue
Integer id;
#NotEmpty
String titre;
Long prix;
#Column(length=10000000)
byte [] photos;
public byte[] getPhotos() {
return photos;
}
String ville;
String categorie;
#Lob
#Column(length=10000000)
byte [] photos;
public Annonce() {
super();
// TODO Auto-generated constructor stub
}
public Annonce( String ville, Long prix, String categorie,
byte[] photos) {
super();
this.ville= ville;
this.prix = prix;
this.categorie = categorie;
this.photos = photos;
}
public Annonce( String categorie, Long prix, String ville, byte[] photos) {
super();
this.ville= ville;
this.categorie = categorie;
this.prix = prix;
this.photos = photos;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getVille() {
return ville;
}
public void setTVille(String ville) {
this.ville = ville;
}
public String getCategorie() {
return categorie;
}
public void setCategorie(String categorie) {
this.categorie= categorie;
}
public Long getPrix() {
return prix;
}
public void setPrix(Long prix) {
this.prix = prix;
}
public byte[] getPhotos() {
return photos;
}
public void setPhotos(byte[] photos) {
this.photos = photos;
}
}
I want to get the last ID (auto increment) saved in the database .