问题:
What I have:我拥有的:
@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
}
What a problem:有什么问题:
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.但是我也不能在继续方法中关闭会话。
What a solution (coarse solution):什么解决方案(粗解):
a) Before session is closed, force hibernate to pull lazy collections a) 在 session 关闭之前,强制休眠拉取惰性集合
entity.getAddresses().size();
entity.getPersons().size();
.... ....
b) Maybe more ellegant way is to use @Fetch(FetchMode.SUBSELECT)
annotation b) 也许更优雅的方法是使用@Fetch(FetchMode.SUBSELECT)
注释
Question:题:
What is a best practice/common way/more ellegant way to do it?什么是最佳实践/常用方法/更优雅的方法? Means convert my object to JSON.意味着将我的对象转换为 JSON。