2012-08-17 117 views
5

我怎麼能映射在Hibernate中一個一對多的關係,其中許多方需要進行分頁?因爲加載一個端對象與它所有的引起內存災難(相關對象的檢索,即使你使用懶惰(即你有上百個或多個相關對象)
使用OneToMany註釋(或等價的xml)不是很有用加載)。
一種可能的方法(這我已在使用)是在DAO實現,在那裏你可以介紹分頁參數添加一個getter方法。不過,我可以看到這並不理想,因爲你失去了一些像級聯這樣的功能(例如,我必須在DAO類中包含setter方法來關聯對象)。此外,你失去了一些OOP的感覺,因爲單側對象沒有檢索其相關的多邊對象的方法。什麼是最好的解決方案?
爲了進一步說明我的觀點,假設我有兩個類,它們之間存在以下關係:A有許多B.
我不能使用OneToMany註釋編寫A.getAllB()方法,因爲有數百個因此,爲了對結果進行分頁,我使用getAllB()方法創建了一個單獨的ADaoImpl類,其中我可以包含分頁參數,一次只返回一頁數據。它是否正確?任何幫助將不勝感激。Hibernate的分頁一對多關係

回答

2

我想我會做你提出同樣的事情:創建需要分頁參數,並返回結果的指定頁面吾道的新方法。是否要讓孩子留在父母對象中取決於你。您可以爲這些對象創建一個瞬態字段。

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」感覺。