I have two user Objects and while I try to save the object using
session.save(userObj);
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:
[com.pojo.rtrequests.User#com.pojo.rtrequests.User@d079b40b]
I am creating the session using
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(); // 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?
@GeneratedValue(strategy=GenerationType.IDENTITY), adding this annotation to the primary key property in your entity bean should solve this issue.
before the position where repetitive objects begin , you should close the session and then you should start a new session
so in this way in one session there is not more than one entities that have the same identifier.
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
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.
I ran into this problem by:
I resolved it by flushing the results after the delete, and clearing the cache before saving the new object
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.