Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

java hibernate orm

205735 просмотра

30 ответа

I have two user Objects and while I try to save the object using


I am getting the following error:

Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:

I am creating the session using

BaseHibernateDAO dao = new BaseHibernateDAO();          

rtsession = dao.getSession(userData.getRegion(),

rttrans = rtsession.beginTransaction();



rtsession.close(); // in finally block

I also tried doing the session.clear() before saving, still no luck.

This is for the first I am getting the session object when a user request comes, so I am getting why is saying that object is present in session.

Any suggestions?

Автор: harshit Источник Размещён: 13.11.2019 11:29

Ответы (30)

167 плюса


I have had this error many times and it can be quite hard to track down...

Basically, what hibernate is saying is that you have two objects which have the same identifier (same primary key) but they are not the same object.

I would suggest you break down your code, i.e. comment out bits until the error goes away and then put the code back until it comes back and you should find the error it.

It most often happens via cascading saves where there is a cascade save between object A and B, but object B has already been associated with the session but not on the same instance of B.

What primary key generator are you using?

The reason I ask is this error is related to how you're telling hibernate to ascertain the persistent state of an object (i.e. whether an object is persistent or not). The error could be happening because hibernate is trying to persist and object that is already persistent. In fact, if you use save hibernate will try and persist that object, and maybe there is already an object with that same primary key associated with the session.


Assuming you have a hibernate class object for a table with 10 rows based on a primary key combination (column 1 and column 2). Now, you have removed 5 rows from the table at some point of time. Now, if you try to add the same 10 rows again, while hibernate tries to persist the objects in database, 5 rows which were already removed will be added without errors. Now the remaining 5 rows which are already existing, will throw this exception.

So the easy approach would be checking if you have updated/removed any value in a table which is part of something and later are you trying to insert the same objects again

Автор: Michael Wiles Размещён: 02.07.2009 07:56

18 плюса

This is only one point where hibernate makes more problems than it solves. In my case there are many objects with the same identifier 0, because they are new and don't have one. The db generates them. Somewhere I have read that 0 signals Id not set. The intuitive way to persist them is iterating over them and saying hibernate to save the objects. But You can't do that - "Of course You should know that hibernate works this and that way, therefore You have to.." So now I can try to change Ids to Long instead of long and look if it then works. In the end it's easier to do it with a simple mapper by your own, because hibernate is just an additional intransparent burden. Another example: Trying to read parameters from one database and persist them in another forces you to do nearly all work manually. But if you have to do it anyway, using hibernate is just additional work.

Автор: Hein Размещён: 20.10.2010 08:45

15 плюса

USe session.evict(object); The function of evict() method is used to remove instance from the session cache. So for first time saving the object ,save object by calling session.save(object) method before evicting the object from the cache. In the same way update object by calling session.saveOrUpdate(object) or session.update(object) before calling evict().

Автор: Rahul N Размещён: 05.10.2012 11:22

9 плюса

This can happen when you have used same session object for read & write. How? Say you have created one session. You read a record from employee table with primary key Emp_id=101 Now You have modified the record in Java. And you are going to save the Employee record in database. we have not closed session anywhere here. As the object that was read also persist in the session. It conflicts with the object that we wish to write. Hence this error comes.

Автор: Prashant Bari Размещён: 04.07.2014 07:45

8 плюса

As somebody already pointed above i ran into this problem when i had cascade=all on both ends of a one-to-many relationship, so let's assume A --> B (one-to-many from A and many-to-one from B) and was updating instance of B in A and then calling saveOrUpdate(A) , it was resulting in a circular save request i.e save of A triggers save of B that triggers save of A... and in the third instance as the entity( of A) was tried to be added to the sessionPersistenceContext the duplicateObject exception was thrown.
  I could solve it by removing cascade from one end.

Автор: redzedi Размещён: 22.11.2012 06:21

4 плюса

I also ran into this problem and had a hard time to find the error.

The problem I had was the following:

The object has been read by a Dao with a different hibernate session.

To avoid this exception, simply re-read the object with the dao that is going to save/update this object later on.


class A{      

       someDaoA.read(myBadAssObject); //Different Session than in class B


class B{

       someDaoB.read(myBadAssObjectAgain); //Different Session than in class A
       myBadAssObjectAgain.fooValue = 'bar';


Hope that save some people a lot of time!

Автор: Frithjof Размещён: 06.03.2012 09:40

4 плюса

I ran into this problem by:

  1. Deleting an object (using HQL)
  2. Immediately storing a new object with the same id

I resolved it by flushing the results after the delete, and clearing the cache before saving the new object

String delQuery = "DELETE FROM OasisNode";
session.createQuery( delQuery ).executeUpdate();
Автор: wbdarby Размещён: 30.06.2013 07:03

4 плюса

You can use session.merge(obj), if you are doing save with different sessions with same identifier persistent object.
It worked, I had same issue before.

Автор: Pavan Kumar Размещён: 24.04.2018 05:20

3 плюса

Get the object inside the session, here an example:

MyObject ob = null;
ob = (MyObject) session.get(MyObject.class, id);
Автор: sock_osg Размещён: 21.06.2010 09:22

2 плюса

Are your Id mappings correct? If the database is responsible for creating the Id through an identifier, you need to map your userobject to that ..

Автор: cwap Размещён: 02.07.2009 12:33

2 плюса

I encountered this problem with deleting an object, neither evict nor clear helped.

 * Deletes the given entity, even if hibernate has an old reference to it.
 * If the entity has already disappeared due to a db cascade then noop.
public void delete(final Object entity) {
  Object merged = null;
  try {
    merged = getSession().merge(entity);
  catch (ObjectNotFoundException e) {
    // disappeared already due to cascade
Автор: TimP Размещён: 27.03.2014 12:38

1 плюс

Check if you forgot to put @GenerateValue for @Id column. I had same problem with many to many relationship between Movie and Genre. The program threw Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session error. I found out later that I just have to make sure you have @GenerateValue to the GenreId get method.

Автор: Thupten Размещён: 27.03.2012 05:07

1 плюс

just check the id whether it takes null or 0 like

if(offersubformtwo.getId()!=null && offersubformtwo.getId()!=0)

in add or update where the content are set from form to Pojo

Автор: Ayan Sarkar Размещён: 07.11.2012 12:42

1 плюс

I'm new to NHibernate, and my problem was that I used a different session to query my object than I did to save it. So the saving session didn't know about the object.

It seems obvious, but from reading the previous answers I was looking everywhere for 2 objects, not 2 sessions.

Автор: DustinA Размещён: 25.09.2013 04:59

1 плюс

@GeneratedValue(strategy=GenerationType.IDENTITY), adding this annotation to the primary key property in your entity bean should solve this issue.

Автор: Jay Размещён: 20.12.2014 12:38

1 плюс

I resolved this problem .
Actually this is happening because we forgot implementation of Generator Type of PK property in the bean class. So make it any type like as

private int id;

when we persist the objects of bean ,every object acquired same ID ,so first object is saved ,when another object to be persist then HIB FW through this type of Exception: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session.

Автор: Ankit Sharma Размещён: 23.02.2015 07:13

1 плюс

before the position where repetitive objects begin , you should close the session and then you should start a new session

session = HibernateUtil.getSessionFactory().openSession();

so in this way in one session there is not more than one entities that have the same identifier.

Автор: engtuncay Размещён: 15.09.2015 06:35

1 плюс

The problem happens because in same hibernate session you are trying to save two objects with same identifier.There are two solutions:-

  1. This is happening because you have not configured your mapping.xml file correctly for id fields as below:-

    <id name="id">
      <column name="id" sql-type="bigint" not-null="true"/>
      <generator class="hibernateGeneratorClass"</generator>
  2. Overload the getsession method to accept a Parameter like isSessionClear, and clear the session before returning the current session like below

    public static Session getSession(boolean isSessionClear) {
        if (session.isOpen() && isSessionClear) {
            return session;
        } else if (session.isOpen()) {
            return session;
        } else {
            return sessionFactory.openSession();

This will cause existing session objects to be cleared and even if hibernate doesn't generate a unique identifier ,assuming you have configured your database properly for a primary key using something like Auto_Increment,it should work for you.

Автор: Rahul Kumar Размещён: 27.12.2015 02:04

1 плюс

I had a similar problem. In my case I had forgotten to set the increment_by value in the database to be the same like the one used by the cache_size and allocationSize. (The arrows point to the mentioned attributes)


CREATED         26.07.16
LAST_DDL_TIME   26.07.16
MIN_VALUE       1
MAX_VALUE       9999999999999999999999999999
CACHE_SIZE      20 <-


@SequenceGenerator(name = "mySG", schema = "my", 
sequenceName = "my_id_seq", allocationSize = 20 <-)
Автор: kaba713 Размещён: 26.07.2016 02:20

1 плюс

Otherwise than what wbdarby said, it even can happen when an object is fetched by giving the identifier of the object to a HQL. In the case of trying to modify the object fields and save it back into DB(modification could be insert, delete or update) over the same session, this error will appear. Try clearing the hibernate session before saving your modified object or create a brand new session.

Hope i helped ;-)

Автор: Arash moradabadi Размещён: 07.11.2016 01:24

1 плюс

I have the same error I was replacing my Set with a new one get from Jackson.

To solve this I keep the existing set, I remove from the old set the element unknown into the new list with retainAll. Then I add the new ones with addAll.


No need to have the Session and manipulate it.

Автор: Ôrel Размещён: 13.04.2017 04:30

1 плюс

Try this. The below worked for me!

In the hbm.xml file

  1. We need to set the dynamic-update attribute of class tag to true:

    <class dynamic-update="true">
  2. Set the class attribute of the generator tag under unique column to identity:

    <generator class="identity">

Note: Set the unique column to identity rather than assigned.

Автор: Explorer_N Размещён: 18.08.2015 10:59

1 плюс

This problem occurs when we update the same object of session, which we have used to fetch the object from database.

You can use merge method of hibernate instead of update method.

e.g. First use session.get() and then you can use session.merge (object). This method will not create any problem. We can also use merge() method to update object in database.

Автор: Jayendra Birtharia Размещён: 04.03.2019 05:53

0 плюса

Another thing that worked for me was to make the instance variable Long in place of long

I had my primary key variable long id; changing it to Long id; worked

All the best

Автор: Ashishakgupta Размещён: 04.08.2009 03:31

0 плюса

You always can do a session flush. Flush will synchronize the state of all your objects in session (please, someone correct me if i'm wrong), and maybe it would solve your problem in some cases.

Implementing your own equals and hashcode may help you too.

Автор: caarlos0 Размещён: 24.11.2011 01:13

0 плюса

You can check your Cascade Settings. The Cascade settings on your models could be causing this. I removed Cascade Settings (Essentially not allowing Cascade Inserts/Updates) and this solved my problem

Автор: user1609848 Размещён: 19.08.2012 10:02

0 плюса

I found this error as well. What worked for me is to make sure that the primary key (that is auto-generated) is not a PDT (i.e. long, int, ect.), but an object (i.e. Long, Integer, etc.)

When you create your object to save it, make sure you pass null and not 0.

Автор: Jaco Van Niekerk Размещён: 15.11.2012 09:49

0 плюса

Does this help?

User userObj1 = new User();
User userObj2 = userObj1;
Автор: George Papatheodorou Размещён: 10.01.2014 02:10

0 плюса

I have solved a similar problem like that:

plan = (FcsRequestPlan) session.load(plan.getClass(), plan.getUUID());
while (plan instanceof HibernateProxy)
    plan = (FcsRequestPlan) ((HibernateProxy) plan).getHibernateLazyInitializer().getImplementation();
Автор: user3132194 Размещён: 03.06.2015 06:24

0 плюса

One workaround to solve this issue is try to read the object back from hibernate cache/db before you make any updates and then persist.


            OrderHeader oh = orderHeaderDAO.get(orderHeaderId);

Note: Keep in mind that this does not fix the root cause but solves the issue.

Автор: Nuwan Размещён: 01.09.2016 06:11
Вопросы из категории :