session.merge() not working as expected in hibernate

Viewed 115

I have just learned about session.merge() in Java and wanted to use in my project. I am querying for a user, and based on the result I receive, either create a new user or update the existing one like this. With user being an entity created beforehand to update the existing user record. I am facing trouble in updating the user.

User QueryUser = (User) session.createQuery(xxx);

org.hibernate.Transaction tx = null;

if (QueryUser == null) {
    System.out.println("Creating New User!!!");
} else {
    System.out.println("Updating User!!!");
    long userId = QueryUser.getId();
    user.setId(userId);
    tx = session.beginTransaction();
    session.merge(user);
    tx.commit();
}

From what I've learned, merge updates persisted entity with data from transient entity provided both of them have same identifiers. So, here user entity should be updated with fields from QueryUser entity, but it is not happening. Can someone please help me find the issue or explain a better way to do it?

0 Answers
Related