0

Am new to hibernate. Am trying to update a table and ended up getting java.sql.SQLIntegrityConstraintViolationException: Duplicate entry for key 'PRIMARY' exception

Am using entityManager.merge() method to update the table.
Below are the table relationships

TableA( 
@ID 
int col A , 
String colB....)

TableB( 
@ID 
int col X , 
@ManyToOne 
@Id 
@JoinColumn(name = "colA",referencedColumnName = "colA") 
TableA tableA ....)

I have used Entitymanager.persist() to insert data in both the tables. Now i want to update the data in TableB. Below is my method for the same

public void update(List<TableBObj> TableBObjList){
    for(TableBObj tableBObj: TableBObjList){
            em.merge(tableBObj);
        }
    }
}

Currently getting "Duplicate entry for key". Seeing the logs merge method isn't running update query but its running insert query instead. Any help appreciated?

RK3
  • 1,221
  • 9
  • 26
  • 37
  • [Did you flush after persisting?](https://stackoverflow.com/questions/17703312/what-does-entitymanager-flush-do-and-why-do-i-need-to-use-it) – Compass Jun 27 '19 at 18:58
  • Hibernate needs to know how the `@Id` columns are generated. Your id columns needs `@GeneratedValue(...)`. See https://vladmihalcea.com/jpa-persist-and-merge/ – Kedar Joshi Jun 27 '19 at 19:00
  • what will be the @GeneratedValue in my case as i dont need any sequence generator. My TableB colx is an enum and other one is a foreign key for TableA – RK3 Jun 27 '19 at 19:05
  • @Compass i have flushed after persist – RK3 Jun 27 '19 at 19:06
  • @RK3 Did you mean to place `@Id` on the `@ManyToOne` association inside the `TableB` entity mapping? That seems a bit strange if you intend to persist the two entities separately and then later update the relationship with them using merge. – Naros Jul 01 '19 at 13:28

0 Answers0