简体   繁体   中英

Spring Hibernate with @Transaction results LazyInitializationException

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 asu = (User) s.get(User.class, id);
    return asu;
}

and Controller

@Controller
public class DummyController {
  @Autowired
  UserDAO userDAO;

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

}

My question is why a simple query for entity User automatically fires query to initialize entity list of SocialCredential ? Is there anything wrong with @Transaction.I am not interested to EAGERLY load list SocialCredential.

The error you have is a very common Hibernate Error.

List<SocialCredential> credentialsList = new ArrayList<SocialCredential>();

You need to get that list, you can use another Query to get that specific list, and set to your user Object.

Session s = sessionFactory.getCurrentSession();
list credentialsList = this.getCredentialsList();
User asu = (User) s.get(User.class, id);
asu.setCredentialsList(credentialsList);    
return asu;

Other way that sometimes work is to do:

Session s = sessionFactory.getCurrentSession();
User asu = (User) s.get(User.class, id);
 **adding this line **
asu.getCredentialsList.get(0);
return asu;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM