Hibernate lazy-load application design

前端 未结 3 826
闹比i
闹比i 2020-12-12 10:14

I tend to use Hibernate in combination with Spring framework and it\'s declarative transaction demarcation capabilities (e.g., @Transactional).

As we all known, hib

3条回答
  •  死守一世寂寞
    2020-12-12 10:23

    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.

提交回复
热议问题