Hibernate does not update object

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; } } 
+4
source share
1 answer

I think it would be better to use "persist" instead of "merge" if you want to persist an entity for the first time.

in your example, there is no need to call "merge" twice, since you are returning the managed object from the first merge and you are changing the entity that you received from the merge, your changes will be automatically saved when the transaction is completed.

0
source

All Articles