type Exception report
message Could not write content: failed to lazily initialize a collection of role: edu.waa.classified.dto.User.products, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->edu.waa.classified.dto.User["products"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: edu.waa.classified.dto.User.products, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->edu.waa.classified.dto.User["products"])
description The server encountered an internal error that prevented it from fulfilling this request.
-
1Please post some codeMohitC– MohitC2015-10-20 05:19:48 +00:00Commented Oct 20, 2015 at 5:19
4 Answers
I just added the @JsonIgnore at the after the @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) annotations.
It worked, but not sure why it worked.
@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "WISHLIST", joinColumns = {
@JoinColumn(name = "userId", referencedColumnName = "id") }, inverseJoinColumns = {
@JoinColumn(name = "productId", referencedColumnName = "id") })
@JsonIgnore
private List<Product> products;
1 Comment
The problem is your FetchType.lazy. When Jackson converts the User Entity, it trys to load the products but the hibernate session is closed.
So adding @JsonIgnore is one way to solve this but when you need the products returned as well, this is no option.
I found this answer which solves the same problem for me and gave me the lazy loaded type: https://stackoverflow.com/a/21760361
The good thing about this solution is, that you can still use the lazy load for products.
Comments
I guess your controller is out of hibernate session. (no @Transactional). But your json list wants to be filled outside that session. But hibernate filled with proxy instead of real data, and outside hibernate session it cannot load that data when you try to access is. JsonIgnore doesn't ask for that data, so it works. Or if you want that Data in your json object, do fetchtype EAGER. Then hibernate load them immediately. If you want that list only in special cases leave it LAZY, but access it then on service layer in a special method , which has annotation @transactional. Then hibernate is able to fill that list.