2017-01-01 93 views
0

我的問題是,我得到LazyInitializationException。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] 

我有一個類

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;} 

2個@ManyToOne關係我使用HttpSession中。 我也試着添加這個屬性spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true但它沒有幫助。我想知道是否有任何解決方案。也試圖在服務中使用事務性的註釋。

+0

你能後的代碼,你是如何獲取數據和確切位置異常拋出。至少完整的堆棧跟蹤。 –

回答

0

問題是你嘗試調用分離的對象。

例如)

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

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

product.getCategory(); // It raises Exception 

我不知道你與這些對象什麼嘗試。但是,你應該重新連接實體的EntityManager就像em.merge(detachedObject)

檢查的EntityManager 的狀態https://vladmihalcea.com/a-beginners-guide-to-jpahibernate-entity-state-transitions/

相關問題