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 ser开发者_开发百科vice 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.
There are numerous options here
- Use lazy-loading or batch fetching
- Use HQL or Criteria queries or even drop down to native SQL to limit the number of results (in other words, instead of navigating the collection, do a query to return the N items you want)
- If caching is an option, you can likely avoid going to the database at least some of the time.
Is there a way to pull just a "certain" object from a large collection without directly invoking the DAO?
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:
- The
@Where
and@BatchSize
annotations (see the 2.4.6.1. Enhance collection settings). - Hibernate's filters (see 2.4.8. Filters).
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.
精彩评论