Sunday, April 6, 2014

Dealing with org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate Java

If you are working in Hibernate framework, then you know that one of the key feature of Hibernate is "lazy initialization", which allows framework to lazily initialize dependencies, relationship or association lazily from database on need basis. For example, if you are dealing with User object, which has relationship with Permission object like one user can have multiple permissions, then Hibernate may choose not to initialize the collection which holds all permissions at the time it initialized User object and instead returns a proxy object. At this point, if you close your session and letter tries to access an attribute from Permission object, you will get "org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate". Why this error comes, because hibernate needs to go database to initialize the proxy object, and connection is already closed. If you remember, what we discussed in difference between get vs load in hibernate that Proxy object is only initialized in Hibernate if you access any attribute other than id itself, that's why you would only see LazyInitializationException if you try to access an attribute other than id. In this article, we will see different scenarios on which you could possibly get "org.hibernate.LazyInitializationException: could not initialize proxy - no Session in Hibernate" and how to solve them appropriately. I have tried to explain reasons which caused the error, and explained the solution as why it will work, but if you still face issues, then feel free to post it here. By the way, good understanding of lazy initialization is also a good Hibernate interview question, so this not only help you to solve this error but also to do well during interviews.
Read more �

No comments:

Post a Comment