Hibernate - How to efficiently fetch a big object graph?
For a project, I have to read a list of objects out of a database. The object type is a big object graph consisting of a lot of associat开发者_JAVA技巧ed objects. When I execute the select query to get a list of all the objects in the database, Hibernate not only executes 1, but 45 additional queries. Still, it seems that the objects are lazy loaded.
But what I need is efficiently loading list of the WHOLE objects. What would be the best way to do this?
I first thought of using fetch joins but with so many associations this could become a real pain. Are there any better solutions?
Fetch joins and caching (or combination thereof) are basically the only ways to improve performance here; whether they will work for you highly depends on what your entities look like and what it is you're trying to do.
Caching is helpful for many-to-one dependencies with (somewhat) limited number of (ideally immutable) instances - e.g. looking up references. Fetch joins can be used for all other one-to-ones and many-to-ones; trying to fetch nested collections gets out of hand very quickly.
One additional trick which is applicable in certain cases is pre-loading (some) lazy dependent entities (if you know what they are beforehand, of course) into session before running your query. That way you don't have to deal with performance / memory issues of 2nd level cache for cases where that's impractical.
All that said, if the 45 additional queries you've mentioned are per entity in your list, you'll probably have to make a trade-off somewhere and cache / fetch some dependencies letting the others being loaded via subsequent selects.
精彩评论