我的问题是我得到了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]
我在一个班级中有两个@ManyToOne关系
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;}
我正在使用HttpSession。
我还尝试添加此属性spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
,但它没有帮助。我想知道是否有任何解决方案。还试图在服务中使用Transactional anotation。
答案 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/