如何在 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”感觉。
关于Hibernate 分页 OneToMany 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12008637/