I am making a restful application and trying to convert a list of objects into json for a specific url (@RequestMapping / @ResponseBody )
I have jackson-hibernate4 and jackson-core ,databind etc in my classpath.
Here is my object that i want to convert in json.
@Entity
@Table(name="Product")
public class Product {
@Id
@Column(name="productId")
@GeneratedValue
protected int productId;
@Column(name="Product_Name")
protected String name;
@Column(name="price")
protected BigDecimal baseprice;
@OneToMany(cascade = javax.persistence.CascadeType.ALL,mappedBy="product",fetch=FetchType.EAGER)
protected List<ProductOption> productoption = new ArrayList<ProductOption>();
@OneToMany(cascade = javax.persistence.CascadeType.ALL,mappedBy="product",fetch=FetchType.EAGER)
protected List<ProductSubOption> productSubOption = new ArrayList<ProductSubOption>();
@ManyToOne
@JoinColumn(name="ofVendor")
protected Vendor vendor;
The two objects inside Product are also POJO'S..
Here is my method that retrieves the list of product
@Override
public List<Product> getMenuForVendor(int vendorId) {
List<Product> result = em.createQuery("from "+Product.class.getName()+" where ofVendor = :vendorId").setParameter("vendorId", vendorId).getResultList();
System.out.println(result.size());
return result;
}
When i try to return this list in my controller I was getting a "Cannot lazily load for json" so i set my objects to be fetched eagerly. Here is my controller
@Autowired
private MenuDaoImpl ms;
@RequestMapping(value = "/{vendorId}", method = RequestMethod.GET)
public @ResponseBody List<Product> getMenu(@PathVariable int vendorId){
List<Product> Menu = Collections.unmodifiableList(ms.getMenuForVendor(vendorId));
return Menu;
}
Now when i hit my url localhost:8080/getMenu/1 I should be getting a json string displayed but I get a big list of errors
WARN : org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Handling of [org.springframework.http.converter.HttpMessageNotWritableException] resulted in Exception
java.lang.IllegalStateException: Cannot call sendError() after the response has been committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:467)
Could not write JSON: Infinite recursion (StackOverflowError) (through reference chain:
I am not sure if I am missing anything. Please guide .
I solved it using @JsonBackReference for @ManyToOne binding and @JsonManagedReference on @OneToMany binding.
Thanks "Sotirios Delimanolis"
The question has already been answered. I am simply putting the link of a good example that clearly explains both the problem and the solution. http://geekabyte.blogspot.in/2013/09/fixing-converterhttpmessagenotwritablee.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With