I use hibernate EntityManager to save an object and then update it. My code looks something like this:
@PersistenceContext(unitName = "demoPU") private EntityManager em; E e = new E(); e.setDescription("Description"); e = em.merge(e); em.flush(); e.setDescription("newDescription"); e = em.merge(e); em.flush();
The class E identifier is generated using @PrePersist.
Sleep logs look something like this:
Hibernate: insert into E (Description, ID) values (?, ?, ?) Hibernate: insert into E (Description, ID) values (?, ?, ?)
So basically sleep mode tries to insert the same object twice with the same identifier. This, in turn, gives the following exception:
org.hsqldb.HsqlException: integrity constraint violation: unique constraint or index violation; SYS_PK_10253 table: POLICY
Can someone tell me why hibernate runs the insert instead of update , although I use merge entity managers to save and update the object? Also, how can I really update the object in this case?
EDIT: class E is as follows:
@Entity @Table(name = "E") public class E { @Id @Column(name="ID",nullable = false) private String id; @Basic(optional = false) @Column(name = "Description", nullable = false) private String Description; // Getters setters etc public String getId(){ if(this.id == null ){ this.setId(UUID.randomUUID().toString()); } return id; } @PrePersist private void verifyPrimaryKeyAssigned(){ getId(); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; Policy other = (Policy) obj; if (getId() == null) { if (other.getId() != null) return false; } else if (!getId().equals(other.getId())) return false; return true; } }
source share