For many years LazyInitializationExceptions have
become most frustrating point of Hibernate. This exception occurs when
you try to access an un-initialised lazy association of a detached
entity.
Entities become detached in three different ways;
So what are the ways to get rid of that Lazy exception? There are several ways available in Hibernate and employed among the community;
So what does this property do? It simply signals Hibernate that it should open a new session if session which is set inside current un-initialised proxy is closed. You should be aware that if you have any other open session which is also used to manage current transaction, this newly opened session will be different and it may not participate into the current transaction unless it is JTA. Because of this TX side effect you should be careful against possible side effects in your system.
Another important point is that this feature only works for proxies whose sessions are closed or their owning entity is evicted from the session. If the entity become detached with session clear then you will still have the lazy problem. According to code comments in Hibernate’s AbstractPersistentCollection class, Hibernate team aims to handle session clear in the next major release.
Entities become detached in three different ways;
- session close
- session clear
- session evict
So what are the ways to get rid of that Lazy exception? There are several ways available in Hibernate and employed among the community;
- You can invoke Hibernate.initialize(proxy) on each lazy attribute before their owning entity becomes detached.
- You have to access their specific properties such as ids before detachment such as x.getLazySet().size() or x.getLazyManyToOneAssoc().getId().
- For web applications you can also employ OpenSessionInViewFilter which keeps session open until the end of view render process so that entities wont become detached before those lazy attributes accessed.
- You can also reattach detached entities before accessing their lazy attributes using session merge or lock operations.
So what does this property do? It simply signals Hibernate that it should open a new session if session which is set inside current un-initialised proxy is closed. You should be aware that if you have any other open session which is also used to manage current transaction, this newly opened session will be different and it may not participate into the current transaction unless it is JTA. Because of this TX side effect you should be careful against possible side effects in your system.
Another important point is that this feature only works for proxies whose sessions are closed or their owning entity is evicted from the session. If the entity become detached with session clear then you will still have the lazy problem. According to code comments in Hibernate’s AbstractPersistentCollection class, Hibernate team aims to handle session clear in the next major release.
No comments:
Post a Comment