Java is a wonderfully powerful language that all programmers are using. Multiple projects have been designed using this language all over the world. And that’s the reason why beginners are also learning Java. When working with the language, it is quite normal to encounter errors. You may get the ‘Hibernate error: a different object with the same identifier value was already associated with the session’. It is one of the common errors that can pop up.
There is no need to get demotivated when you get this error warning as we are here to help you solve the issue. We have simple ideas to fix the error you are getting. First, let’s have look at how error occurs
How the error occurs
The error message ‘Hibernate error: a different object with the same identifier value was already associated with the session’ shows up when you try to call session.saveOrUpdate(myAObject). This is what you get in return
Hibernate error: "a different object with the same identifier value was already associated with the session: C
We have a quick and simple solution to fix the error. Check out the next section
How to Fix the Error ‘Hibernate error: a different object with the same identifier value was already associated with the session’
The cause of the error is that the B objects used in the program are not related to the C object Java. In actual, they refer to the same row of the database the like same primary key, but they generally are separate copies.
The function of the hibernate session is to keep a track of entities and also manage which object of Java corresponds to which row having the same primary key.
Solution To fix the Issue
To Solve the ‘Hibernate error: a different object with the same identifier value was already associated with the session’ warning, you need to ensure the B objects’ entities should refer to the same row. With that, it is referring to the same instance of object C.
The alternate way to fix the error is to switch the cascading for the member variable off. With this, C is not persisted when B is. So, basically you need to manually save C separately. In the case, C is a type/category table, it perhaps makes sense. This way, you simply fix the issue.
Conclusion
Here, in this article, we guide you on how to tackle ‘Hibernate error: a different object with the same identifier value was already associated with the session’ in an efficient way. Trying this fix can make the error warning go away.
I hope it proves helpful for you!
Don’t forget to drop a message below! Your feedback is always encouraged!
Reference Source: https://stackoverflow.com/questions/16246675/hibernate-error-a-different-object-with-the-same-identifier-value-was-already-a