0

Consider entity

public class User {
...
@OneToMany(cascade = CascadeType.ALL)
List<SocialCredential> credentialsList = new ArrayList<SocialCredential>  ();
}

with DAO Implementation method

@Transactional
@Override
  public User getUser(long id){
  Session s = sessionFactory.getCurrentSession();
  User u = (User) s.get(User.class, id);
  return u;
}

and Controller

@Controller
      public class DummyController {
       @Autowired
       UserDAO userDAO;

       public void anyMethodAccessedByGetORPost(){
         User u= userDAO.getUser(1L);
       }
      }

A simple query for entity User automatically fires query to initialize entity list of SocialCredential ? Ultimately it leads to LazyInitializationException.I came to know to know about OpenSessionInViewInterceptor which can solve the issue.How can I apply the same. I am already following http://www.jroller.com/kbaum/entry/orm_lazy_initialization_with_dao but with no success so far.

GAMITG
  • 3,810
  • 7
  • 32
  • 51
Gufran Khurshid
  • 888
  • 2
  • 9
  • 28

1 Answers1

-1

A simple query for entity User automatically fires query to initialize entity list of SocialCredential ?

It depends on underlying persistence API's default fetch type. Refer this question

Ultimately it leads to LazyInitializationException -- This is probably you are trying access credentialsList collection after session has been closed.

Replace DAO's getUser(Long id) method with below code may solve LazyInitializationException.

@Transactional
@Override
public User getUser(long id){
   Session s = sessionFactory.getCurrentSession();
   User u = (User) s.get(User.class, id);
   if (u != null) {
      u.getCredentialsList(); //it loads the SocialCredentials before session closes.
   }
   return u;
}
Community
  • 1
  • 1
Lovababu Padala
  • 2,415
  • 2
  • 20
  • 28
  • Thanks for that, but that's not the answer of my question .Its a hack to eargerly load the detached entities which can be easily done using FetchType.EAGER.As my question states I am interested in implementing OpenSessionInViewInterceptor. – Gufran Khurshid Oct 26 '15 at 09:53