I am making a sedative application and trying to convert a list of objects to json for a specific URL (@ RequestMapping / @ ResponseBody)
I have jackson-hibernate4 and jackson-core, databind etc in my class path.
Here is my object that I want to convert to 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;
Two objects inside Product are also POJO'S.
Here is my method that retrieves a list of products
@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 to my controller, I get the message "Can not lazily load for json", so I want my objects to be loaded impatiently. 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 that I find my localhost url: 8080 / getMenu / 1, I should get the json string, but I get a large 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'm not sure something is missing. Please guide.