I’ve heard several times that several problems arise in hibernate (especially when using lazy loading). Which are the most common and what can be done about them?
I’ve heard several times that several problems arise in hibernate (especially when using lazy
Share
The most common probably is the n+1 select problem, when lazy loading of a collection results in hitting the DB with n+1 separate queries instead of a single join query.
The antidote to such issues is common sense 🙂 I believe that all relevant sources (first and foremost the Hibernate reference) discuss this (and other related) issues extensively, together with resolutions and workarounds. In brief, you should not copy recipes blindly from the cookbook – measure the performance of your code and tune it accordingly. If you see too many selects issued, you can selectively switch from lazy loading to join or subselect fetching strategy for that specific property/class/query. (Note that both of these have their own potential drawbacks, so again, performance measurement is key.)
A different, albet much rarer, problem arises when the client code depends on the actual type of an entity/property (e.g. by testing it with
instanceof. Such code breaks if it encounters a proxy object, which is not an instance of the concrete class it stands for. However, it is not the best idea to write such code anyway, and it should very rarely be necessary. However, sometimes it is inherited with legacy code, thus causing a conflict which may be difficult to work around.