Tutorial :Good way to handle large collection in a domain model - with JPA/Hibernate ORM?



Question:

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.


Solution:1

There are numerous options here

  1. Use lazy-loading or batch fetching
  2. 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)
  3. If caching is an option, you can likely avoid going to the database at least some of the time.


Solution:2

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:

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »