问题描述
我有什么:
@Entity
public class MyEntity {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
@JoinColumn(name = "myentiy_id")
private List<Address> addreses;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
@JoinColumn(name = "myentiy_id")
private List<Person> persons;
//....
}
public void handle() {
Session session = createNewSession();
MyEntity entity = (MyEntity) session.get(MyEntity.class, entityId);
proceed(session); // FLUSH, COMMIT, CLOSE session!
Utils.objectToJson(entity); //TROUBLES, because it can't convert to json lazy collections
}
有什么问题:
问题是我无法在会话关闭后拉延迟收集.但是我也不能在 proceed 方法中关闭会话.
The problem is that I can't pull lazy collection after session has been closed. But I also can't not close a session in proceed method.
什么解决方案(粗略的解决方案):
a) 在会话关闭之前,强制休眠拉取惰性集合
a) Before session is closed, force hibernate to pull lazy collections
entity.getAddresses().size();
entity.getPersons().size();
....
b) 也许更优雅的方式是使用 @Fetch(FetchMode.SUBSELECT)
注释
b) Maybe more ellegant way is to use @Fetch(FetchMode.SUBSELECT)
annotation
问题:
什么是最佳实践/常用方法/更优雅的方法?意味着将我的对象转换为 JSON.
What is a best practice/common way/more ellegant way to do it? Means convert my object to JSON.
推荐答案
在 @Transactional
中使用 Hibernate.initialize()
来初始化惰性对象.
Use Hibernate.initialize()
within @Transactional
to initialize lazy objects.
start Transaction
Hibernate.initialize(entity.getAddresses());
Hibernate.initialize(entity.getPersons());
end Transaction
现在在事务之外,您可以获得惰性对象.
Now out side of the Transaction you are able to get lazy objects.
entity.getAddresses().size();
entity.getPersons().size();
这篇关于Hibernate:拉取所有惰性集合的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!