use*_*194 5 hibernate hibernate-onetomany
如何在Hibernate中映射一对多关系,其中多方需要进行分页?(即你有数百个或更多的相关对象)
使用OneToMany批注(或其xml等价物)是没用的,因为加载单方对象会检索所有相关对象导致内存灾难(即使你使用延迟加载) .
一种可能的方法(我已经在使用)是在DAO实现中添加一个getter方法,您可以在其中引入分页参数.但是,我可以看到这并不理想,因为你失去了一些功能,比如级联(例如,我必须在DAO类中包含setter方法来关联对象).此外,您失去了一些OOP意识,因为单侧对象没有检索其相关多方对象的方法.什么是最好的解决方案?
为了进一步说明我的观点,假设我有两个类,它们之间有以下关系:A有很多B.
我不能使用OneToMany注释编写A.getAllB()方法,因为有数百个B与之相关因此,为了对结果进行分页,我使用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();
}
}
Run Code Online (Sandbox Code Playgroud)
我知道你所说的破坏你对代码的面向对象感觉是什么意思。但实际上分页是数据层的功能。采用第一个解决方案可能会恢复一些美好的“OO”感觉。
| 归档时间: |
|
| 查看次数: |
697 次 |
| 最近记录: |