[英]Hibernate paginated OneToMany relationship
如何在Hibernate中映射一對多關系,其中多方需要進行分頁? (即你有數百個或更多的相關對象)
使用OneToMany批注(或其xml等價物)是沒有用的,因為加載單側對象會檢索所有相關對象導致內存災難(即使您使用延遲加載)。
一種可能的方法(我已經在使用)是在DAO實現中添加一個getter方法,您可以在其中引入分頁參數。 但是,我可以看到這並不理想,因為你失去了一些功能,比如級聯(例如,我必須在DAO類中包含setter方法來關聯對象)。 此外,您失去了一些OOP意識,因為單側對象沒有檢索其相關多方對象的方法。 什么是最好的解決方案?
為了進一步說明我的觀點,讓我們說我有兩個類,它們之間有以下關系:A有很多B.
我不能使用OneToMany注釋編寫A.getAllB()方法,因為有數百個B與A相關。因此,為了對結果進行分頁,我使用getAllB()方法創建一個單獨的ADaoImpl類,我可以在其中包含分頁參數一次只返回一頁數據。 這個對嗎? 任何幫助將不勝感激。
我想我會做同樣的建議:在我的dao上創建一個新的方法,它接受分頁參數並返回指定的結果頁面。 是否要將子項保留在父對象中取決於您自己。 您可以為這些對象創建瞬態字段。
public class Parent {
@Transient
private List<Child> children;
}
public class ParentDao {
// Solution 1 - You can keep the parent/child association
public void loadChildren(Parent parent, int firstResult, int maxResults) {
// do your query
parent.setChildren(query.list());
}
// Solution 2 - Or just have your dao directly return the children and remove the list from Parent
public List<Children> getChildren(Parent parent, int firstResult, int maxResults) {
// do your query
return query.list();
}
}
我知道你打破你對代碼的OO感覺是什么意思。 但真正的分頁是數據層的功能。 采用第一種解決方案可能會恢復一些不錯的“OO”感覺。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.