java - how can to resolve org.hibernate.LazyInitializationException? -


org.hibernate.lazyinitializationexception: failed lazily initialize collection of role: com.t4bt.gov.persistence.entities.experts.institutaionlist, no session or session closed

you provide little details in question (code?), have generalized answer regarding lazy loading. in future, if want answers, please provide concrete information actual problem, descriptions have tried solve it.

a lazyinitialization occurs when try access lazily loaded property after session closed (which after transaction has ended). way lazy initalization works doesn't fetch lazily initialized properties when fetch object, when try access it, hibernate query database fetch it.

the following produce such error:

public class {     [...]     @onetomany(fetch = fetchtype.lazy)     private list<somethingelse> somethingelse;      public list<somethingelse> getsomethingelse() {         return somethingelse;     } }  public class somethingdao {     @inject     private entitymanager em;      @transactional     public getbyid(final integer id) {         return em.find(something.class, id);     } }  public class somethingservice {     @inject     private somethingdao dao;      public list<somethingelse> getsomethingelseforsomething(final integer somethingid) {          final something = dao.getbyid(somethingid);         return something.getsomethingelse() //throws lazyinitializationexception     } } 

here transaction (and session) exists in dao-class. once leaving dao-method, session gone. so, when try access lazy-loaded property in service, fail when hibernates tries contact session in order retrieve it.

to avoid this, there several possibilities.

  1. change annotation of something-class @onetomany(fetch = fetchtype.eager) property no longer lazy-loaded, no more problems.
  2. add @transactional service-method. call getsomethingelse() in same transaction fetching of something-object, , session still alive when doing so.
  3. add call getsomethingelse() in dao-method. initialize property (fetch database) before leaving dao-class (and transaction), , available outside transaction, no need communicate session in order retrieve it.

Comments

Popular posts from this blog

ios - iPhone/iPad different view orientations in different views , and apple approval process -

java Extracting Zip file -

C# WinForm - loading screen -