Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA EntityExistsException

Tags:

java

jpa

The problem that I'm currently facing is the following:

Exception in thread "main" javax.persistence.EntityExistsException: a different object with the same identifier value was already associated with the session: [de.entities.Genre#28]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1359)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1316)
at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:881)
at de.model.DatabaseBuilder.importData(DatabaseBuilder.java:87)
at de.main.Main.main(Main.java:55)

So the Exception tells me that I want to insert two different objects with the same primary key id.

All my datas I want to insert into a database using JPA are coming from an XML file. I parse this file with a SAXParser. Of course there are many genre entries with the id 28 because many movies have the same genre.

If I use auto-generated ids, the data wont be correct anymore because all id's are correctly given by the XML file.

How can I solve this problem? Why isn't JPA not just ignoring the fact, that this object is already present in the database and just inserting the ids of the movies and the genres in my m:n table?

like image 624
user1882812 Avatar asked Oct 29 '25 07:10

user1882812


1 Answers

Either you are directly calling persist on your Genre instances, or you are calling persist on movie and the movie->Genre mapping has cascade persist. JPA requires providers to throw an exception when persist is called on a detached entity, since persist means you want the provider to insert it, and it is detached because it already exists. So you will get an exception. Sounds like your parser is not able to tell that the Genre entities are the same instance, and so is creating multiple instances of the same data. If this cannot be fixed, you might try using merge instead. Merge will check first if the entity instance is new or detached. If it is new, it will insert, while if it is detached, it will retrieve the data and update it in the database.

Other options would be to make sure you are not calling persist on detached Genre instances. Remove the cascade persist settings on relationships, and ensure that you manually call persist or merge on new Genre instances rather than rely on cascade persist settings.

like image 95
Chris Avatar answered Oct 31 '25 13:10

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!