Hibernate lazy-load application design Hibernate lazy-load application design java java

Hibernate lazy-load application design


As we all known, hibernate tries to be as non-invasive and as transparent as possible

I would say the initial assumption is wrong. Transaparent persistence is a myth, since application always should take care of entity lifecycle and of size of object graph being loaded.

Note that Hibernate can't read thoughts, therefore if you know that you need a particular set of dependencies for a particular operation, you need to express your intentions to Hibernate somehow.

From this point of view, solutions that express these intentions explicitly (namely, 2, 4 and 7) look reasonable and don't suffer from the lack of transparency.


I am not sure which problem (caused by lazyness) you're hinting to, but for me the biggest pain is to avoid losing session context in my own application caches. Typical case:

  • object foo is loaded and put into a map;
  • another thread takes this object from the map and calls foo.getBar() (something that was never called before and is lazy evaluated);
  • boom!

So, to address this we have a number of rules:

  • wrap sessions as transparently as possible (e.g. OpenSessionInViewFilter for webapps);
  • have common API for threads/thread pools where db session bind/unbind is done somewhere high in the hierarchy (wrapped in try/finally) so subclasses don't have to think about it;
  • when passing objects between threads, pass IDs instead of objects themselves. Receiving thread can load object if it needs to;
  • when caching objects, never cache objects but their ids. Have an abstract method in your DAO or manager class to load the object from 2nd level Hibernate cache when you know the ID. The cost of retrieving objects from 2nd level Hibernate cache is still far cheaper than going to DB.

This, as you can see, is indeed nowhere close to non-invasive and transparent. But the cost is still bearable, to compare with the price I'd have to pay for eager loading. The problem with latter is that sometimes it leads to the butterfly effect when loading single referenced object, let alone a collection of entities. Memory consumption, CPU usage and latency to mention the least are also far worse, so I guess I can live with it.


A very common pattern is to use OpenEntityManagerInViewFilter if you're building a web application.

If you're building a service, I would open the TX on the public method of the service, rather than on the DAOs, as very often a method requires to get or update several entities.

This will solve any "Lazy Load exception". If you need something more advanced for performance tuning, I think fetch profiles is the way to go.