Anand Godar
Anand Godar

Reputation: 129

Spring MVC :could not initialize proxy - no Session (through reference chain)

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.

Upvotes: 4

Views: 21604

Answers (4)

Anand Godar
Anand Godar

Reputation: 129

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;

Upvotes: 8

kapishreshth
kapishreshth

Reputation: 4098

I also came through the same problem. I just added the below annotation to my Entity class (Just before the entity class). It does the job for sure.

@Entity @Table(name="Country") @Proxy(lazy = false) public class Country {}

Upvotes: 1

buettner123
buettner123

Reputation: 414

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.

Upvotes: 4

Michael Hegner
Michael Hegner

Reputation: 5823

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.

Upvotes: 1

Related Questions