I use Hibernate

I load the User object like this:

public class Queries { public static <T> T firstOrNull(Query query) { List<T> result = query.list(); return result.size() > 0? result.get(0) : null; } } @Repository public class UserDAOImpl implements UserDAO { @Override @Transactional(readOnly = true) public User byEmail(String email) { Session session = (Session) entityManager.getDelegate(); User u = Queries.firstOrNull( session.createQuery("from User u where u.email = '" + email + "'")); return u; } } 

And then I kind of understand that in fact, the User will return, not the proxy, only now can I update it this way:

  - Загрузить User используя DAO - User.setName(...) - DAO.update(User) 

Because when I try to execute this code (which it does hidden, what I listed above):

 User u = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (name != null) u.setName(name); accountService.update(u); 

I get an exception:

 org.hibernate.LazyInitializationException: could not initialize proxy - no Session 

    1 answer 1

    When executing this code

     User u = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (name != null) u.setName(name); accountService.update(u); 

    You pull the user not from the database, but from Spring Security. It hangs in memory there and cannot be changed. If you want to remember the name of the user and not pull it out of the database, but with an update, then it is best to get getReference (Id) and set the name to the selector. Then only one line with the update will fly to the database. And be sure to do it in a single transaction.