問題:
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。