LazyInitializationException could not initialize proxy - no Session

4.1k views Asked by At

My problem is that I'm getting LazyInitializationException.

org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:148) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:266) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:73) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at sk.kristian.dienes.eshop.entity.SubCategory_$$_jvsta89_5.hashCode(SubCategory_$$_jvsta89_5.java) ~[main/:na]
at sk.kristian.dienes.eshop.entity.Product.hashCode(Product.java:18) ~[main/:na]

I have two @ManyToOne relationships in one class

public class Product implements Serializable{

@Id
@Column(name = "id")
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_category")
private Category category;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "id_sub_category")
private SubCategory subCategory;
}

@Entity
@Data
public class SubCategory implements Serializable {
   @OneToMany(mappedBy = "subCategory", cascade = CascadeType.ALL,fetch = FetchType.EAGER)
   private List<Product> products;
 }

 @Entity
 @Data
 public class Category implements Serializable {
    @OneToMany(mappedBy = "category", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Product> products;}

I'm using HttpSession. I've also tried to add this property spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true but It did not helped. I would like to know if there is any solution. Also tried to use Transactional anotation in services.

1

There are 1 answers

0
Jaehyun Shin On

The problem is you try to call object that is detached.

For example)

Product product = em.find(Product.class, id)

// somewhere `em.detach(product)` is called.

product.getCategory(); // It raises Exception

I don't know what you try with those objects. But you should reattach entity to EntityManager like em.merge(detachedObject)

Check state of EntityManager https://vladmihalcea.com/a-beginners-guide-to-jpahibernate-entity-state-transitions/