I have the following use case:
When a user object is updated, we have to verify the uniqueness of username. The business rule alows a user to change their username, so we first load the user by username to check that the new username is unique. The updated user object is a detatched object, so when we save the detached object we have to merge it if it is in session from the load. If this is a new record, or if the username has changed, the object is not in the session and we just issue a saveOrUpdate() without a merge.
Here is my saveUser method:
Code:
public User saveUser( User user )
{
SessionImplementor session = (SessionImplementor) HibernateSessionManager.getSession();
if (user.getId() == null)
{
//this is a new user...just save it
session.save( user );
}
else
{
final PersistenceContext persistenceContext = session.getPersistenceContext();
EntityKey key = new EntityKey( user.getId(), session.getEntityPersister( null, user ) , session.getEntityMode() );
if ( persistenceContext.containsEntity( key ) )
{
user = (User)session.merge( user );
}
else
{
session.saveOrUpdate( user );
}
}
return user;
}
Is this a good solution? Is this a case for a saveOrUpdateMerge() method?