Resolving NonUniqueObjectException in Hibernate during Session Save Operation

Question

How can I resolve the Hibernate error: org.hibernate.NonUniqueObjectException when saving multiple user objects in the same session?

BaseHibernateDAO dao = new BaseHibernateDAO();
 rtsession = dao.getSession(userData.getRegion(), BaseHibernateDAO.RTREQUESTS_DATABASE_NAME);
 rttrans = rtsession.beginTransaction();
 rttrans.begin();

 rtsession.save(userObj1);
 rtsession.save(userObj2);

 rtsession.flush();
 rttrans.commit();
 rtsession.close();

Answer

The org.hibernate.NonUniqueObjectException occurs when you try to save or merge an entity into a Hibernate session, but another object with the same identifier already exists in that session. This situation commonly arises when dealing with multiple objects that are intended to represent the same database record, but Hibernate has already associated a different instance of that data with the session.

// Example of using merge instead of save
User userObj = //... fetch or create a user object
generatedUser = (User) rtsession.merge(userObj);
rtsession.flush(); // Many other operations can follow here.

Causes

  • Multiple instances of the same entity with the same primary key are present in the session.
  • You are trying to save or update an entity that was already persisted in the current session but with a different instance.
  • Improper handling of session and transaction management, leading to stale instances lingering in the session.

Solutions

  • Ensure that only one instance of the entity with a given primary key is associated with the session at a time.
  • Use `session.merge()` instead of `session.save()` if you are unsure whether the object is already associated with the session.
  • Consider using `session.clear()` carefully, as clearing the session will detach all entities. Ensure transactional boundaries are well managed.

Common Mistakes

Mistake: Not checking for existing object instances in the session before saving a new object with the same identifier.

Solution: Always check if the object is already present in the session using `session.contains(object)` before saving.

Mistake: Assuming session.clear() will automatically fix the NonUniqueObjectException without proper understanding of its consequences.

Solution: Use session.clear() with caution and ensure that you know what entities you are detaching.

Helpers

  • Hibernate
  • org.hibernate.NonUniqueObjectException
  • Hibernate session save error
  • Multiple user objects Hibernate
  • Session management in Hibernate

Related Questions

⦿How to Create a Unique List of Objects in Java?

Learn how to maintain a list of unique objects in Java without duplicates using various techniques.

⦿Why Does the Calculation Between March 30 and March 1, 2020, Return 28 Days Instead of 29?

Discover why calculating the date difference between March 30 and March 1 2020 yields 28 days instead of 29. Understand the impact of time zones.

⦿How Can I Make a Private Method Public for Testing Without Breaking Encapsulation?

Learn how to create a custom annotation to expose private methods for testing while maintaining encapsulation in Java.

⦿How to Optimize For-Comprehensions and Loops in Scala for Performance?

Learn effective strategies to enhance the performance of forcomprehensions and loops in Scala especially in Project Euler problems.

⦿Understanding the Importance of Pattern.compile() in Java Regular Expressions

Discover the significance of Pattern.compile and why its essential for using regex in Java. Learn best practices and common mistakes.

⦿How to Change the Icon of a JFrame in Java

Learn how to customize the JFrame icon in Java with simple code examples and troubleshooting tips.

⦿How to Handle Application Cleanup on Received Interrupt Signals in Java

Learn how to manage cleanup tasks in Java applications when receiving interrupt signals such as SIGTERM especially during logout operations.

⦿How to Create a List of Primitive Integers in Java?

Learn how to create a List of primitive int in Java and explore alternatives like Integer objects and arrays.

⦿Is it Acceptable to Use Try-Catch for Null Checks Instead of Verbose Null Checking?

Explore the pros and cons of using trycatch for null checks compared to verbose checks in Java and how to handle nested object access safely.

⦿How to Organize JUnit Test Classes and Code Packages in a Java Project?

Discover best practices for structuring JUnit test classes and source code packages in Java including naming conventions and using Maven.

© Copyright 2025 - CodingTechRoom.com