46539

Duplicate entry for key 'PRIMARY' in JPA/Hibernate

Question:

I have many-to-many relation in mysql database (Module -< Module_has_Subject >- Subject). Entites were generated by Eclipse, I added method 'add' in both classes. I use JBoss AS7/Hibernate. When I call persist method in EJB, I get org.hibernate.exception.ConstraintViolationException: Duplicate entry '3' for key 'PRIMARY'. I know it must be a trivial mistake, but i just don't see it. I went through most related problems here on Stackoverflow and roseindia (I added cascade, targetEntity,...) and still without success. Entities for tables are as such:

Module.java

@Entity @Table(name="Module") public class Module implements Serializable { @Id @Column(unique=true, nullable=false) private int idModule; //bi-directional many-to-many association to Subject @ManyToMany(mappedBy="modules", fetch=FetchType.EAGER,targetEntity=entity.Subject.class,cascade=CascadeType.ALL) private List<Subject> subjects; public void addSubject(Subject subject) { if(subject.getModules() == null) { subject.setModules(new ArrayList<Module>()); } if(getSubjects() == null) { setSubjects(new ArrayList<Subject>()); } if (!getSubjects().contains(subject)) { getSubjects().add(subject); } if (!subject.getModules().contains(this)) { subject.getModules().add(this); } } ...}

Subject.java

@Entity @Table(name="Subject") public class Subject implements Serializable { @Id @Column(unique=true, nullable=false) private int idSubject; //bi-directional many-to-many association to Module @ManyToMany(fetch=FetchType.EAGER, targetEntity=entity.Module.class,cascade=CascadeType.ALL) @JoinTable( name="Module_has_Subject" , joinColumns={ @JoinColumn(name="Subject_idSubject", nullable=false, referencedColumnName="idSubject") } , inverseJoinColumns={ @JoinColumn(name="Module_idModule", nullable=false, referencedColumnName="idModule") } ) private List<Module> modules; public void addModule(Module module) { if(getModules() == null) { setModules(new ArrayList<Module>()); } if(module.getSubjects() == null) { module.setSubjects(new ArrayList<Subject>()); } if (!getModules().contains(module)) { getModules().add(module); } if (!module.getSubjects().contains(this)) { module.getSubjects().add(this); } } ...}

SubjectEJB.java

... Subject subject = new Subject(); for(Module module : subjectModules) { subject.addModule(module); } em.persist(subject); em.flush(); ...

Answer1:

I don't know if you managed to solve your problem yet, but I have just had exactly the same problem.

In my @OneToMany mapping I used Cascade.ALL which resulted in 2 records being saved when I attempted to save the entity. (duplicated data, different ID's)

After scrolling on the web, I found this <a href="http://forums.codeguru.com/showthread.php?t=511992" rel="nofollow">http://forums.codeguru.com/showthread.php?t=511992</a>, so I changed from CascadeType.ALL to {CascadeType.PERSIST, CascadeType.MERGE}, which caused the error you have "ConstraintViolationException: Duplicate entry '9-2-2012-05-30' for key 'PlayerId'"

Finally I removed Cascade.MERGE and was left with CascadeType.PERSIST which fixed the duplicate entry error and the duplicated records.

As a point, if I use just MERGE or just PERSIST, I get no errors and no duplicated data

Maybe try with MERGE and PERSIST, if you get errors, try with just MERGE.

It is not ideal, but hope it helps.

Chris

Recommend

  • Symfony2 - ReferencedColumnName id is null
  • Doctrine join bypass lazy loading
  • 1 to 1..0 relationship in an embedded form with doctrine
  • Cascade persist error with JPA and EclipseLink on ManyToOne relationship
  • hibernate cascade - update child to null
  • Django/Python: How to iterate through a list in a dictionary for migration/migrate data
  • could not insert select SCOPE_IDENTITY() fluent nhibernate one to many
  • How to monitor transaction isolation level changes in SQL Profiler or in any other tool
  • Hibernate one-to-many mapping eager fetch not working
  • Passing and ArrayList through intent
  • Serializing socket
  • Google Maps getMap returns null
  • Type safe keys with Entity Framework model
  • Cannot invoke my method on the array type int[]
  • Doctrine/Symfony entity generator and generating entity from one table
  • Regarding starting the threads on a condition
  • Why cepheus don't send int without quotes to orion?
  • GAE: Way to get reference to an HttpSession from its ID?
  • Force show.bind execution
  • Groovy: Unexpected token “:”
  • Replace value with Factor in r data.table
  • How to access EntityManager inside Entity class in EJB3
  • Repeat a vertical line on every page in Report Builder / SSRS
  • Opengl-es onTouchEvents problem or a draw problem? [closed]
  • Delete MySQLi record without showing the id in the URL
  • Unanticipated behavior
  • Cannot Parse HTML Data Using Android / JSOUP
  • Comma separated Values
  • How to delete a row from a dynamic generate table using jquery?
  • json Serialization in asp
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • JTable with a ScrollPane misbehaving
  • Trying to get generic when generic is not available
  • Java static initializers and reflection
  • How to stop GridView from loading again when I press back button?
  • unknown Exception android
  • Observable and ngFor in Angular 2
  • failed to connect to specific WiFi in android programmatically
  • Unable to use reactive element in my shiny app
  • How can I use threading to 'tick' a timer to be accessed by other threads?