@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Integer createUsers(final Collection<MyUser> myUsers) {
final Session session = sessionFactory.getCurrentSession();
for (final MyUser myUser : myUsers) {
/*create auto id from db and asscoiate object with session */
session.save(myUser);
myUser.setPassword("password");
}
return myUsers.size();
}
The new password is automatically saved to db becuase object is asscoiated with session. Any further changes to myUser within this method/session are now persisted to database unless the object instance is detached/evicted from session.
When the method has completed the transaction is closed, and the session out of scope; if I returned a MyUser object from this method any further changes outside of this method (eg temporary changes in my controller) are not persisted to database (unless of course I associate with another session and transaction) ?
Once this method has executed the transaction will be committed (or rolled back) and the session will be flushed and closed. Therefore each User object will have the value password set to ‘password’ as you say.
However, once the session is closed the User objects are in a detached state (persisted but not attached to an active session).
If you want to persist any further changes you would have to call session.update(user) to attach the MyUser to a new session within a new transaction.
However, if this Transactional method is called from another Transactional method the MyUser objects will not be detached until that transaction ends.