我的域类中有一些 OneToMany
子集合,它们可能会随着时间的推移而增长以容纳数百或(很可能)数千个实例。然而,通常父母真正需要的只是“第一个”孩子或“最后一个”孩子或“最大”的孩子。让父实例循环遍历从数据库加载的大量对象集合似乎效率很低。
另一方面,我不想因为持久性问题而污染我的域模型,并开始必须在域类中使用我的 DAO 来执行查询。
我可能会将这些查找放在我的服务方法中,但我真的更喜欢将此登录名放在它所属的域中 - 试图避免“贫血域”反模式。
有没有一种方法可以从大集合中提取“特定”对象而不直接调用 DAO?我忽略了一些 JPA ORM 映射功能?
编辑:应用程序是分层设计的,领域模型层位于底部——它不依赖于其他任何东西。接下来是持久层,它实现 DAO 并依赖于域层。在它们之上是一个服务层,我试图通过将业务逻辑下推到域层来使其尽可能薄。
I have some OneToMany
child collections in my domain classes that may grow over time to hold hundreds or (very likely) thousands of instances. However, often times the only thing the parent really needs is the "first" child or the "last" child or the "biggest" child. Having the parent instance loop through a large collection of objects loaded from the database seems inefficient.
On the other hand, I do not want to pollute my domain model with persistence concerns and start having to use my DAO's within the domain classes to execute queries.
I might potentially put these lookups in my service methods, but I really prefer to put this login in my domain where it belongs -- trying to avoid the "anaemic domain" anti-pattern.
Is there a way to pull just a "certain" object from a large collection without directly invoking the DAO? Some JPA ORM mapping capability I've overlooked?
Edit: The application is design in layers with the domain model layer at the bottom -- it depends on nothing else. Next to it is the persistence layer which implements DAOs and depends on the domain layer. Above both of them is a service layer which I am trying to keep as thin as possible by push business logic down into the domain layer.
发布评论
评论(2)
这里有很多选项
There are numerous options here
我不知道标准 JPA 功能允许这样做,我想我会在这里使用自定义查询(“JPA 不能很好地处理大型集合”是随处可见的内容)。
以防万一,也许可以看看一些专有功能,例如:
@Where
和@BatchSize
注释(请参阅 2.4.6.1. 增强集合设置)。我不确定 @Where 注释会有那么有用(除非您为常见用例创建一个特殊实体和一个“胖”实体)。然而,过滤器在这里可能真的很有趣。我从来没有用过它们。
I'm not aware of a standard JPA feature allowing this and I think I would use custom queries here ("JPA doesn't deal well with large collections" is something you'll find everywhere).
Just in case, maybe have a look at some proprietary features such as:
@Where
and@BatchSize
annotations (see the 2.4.6.1. Enhance collection settings).I'm not sure the
@Where
annotation will be be that helpful (unless you create a special entity for the common use cases and a "fat" one). However, filters might be really interesting here. I've never used them tough.