EntityManager em.remove() and em.persist() not reflected in same context while changes in Entity are reflected

StackOverflow https://stackoverflow.com/questions/18631879

  •  27-06-2022
  •  | 
  •  

Question

I am calling a

 SomeEntity someEntity = em.find(EntityPK.Class,entityPK);
 em.Remove(entityPK);

and then persist on same primary key

 em.persist(someEntity)

SQLIntegrityContraintViolatinException is thrown that entity with primary key already exist.

while if I changes

someEntity.setName("Test");

and then gets the same entity back with

someEntity = em.find(EntityPK.Class,entityPK);

it gives me back updated someEntity with

 someEntity.getName()

returns 'Test'.

Changes in the someEntity are reflected while its removal is not reflected.

I am new to the JPA and any help would be appreciated.

Was it helpful?

Solution

Reincarnating objects is normally not a good idea. It is better to use a new id for a new object, such as a generated id.

If you must reincarnate and object, try doing it in a separate transaction, or at least call flush() after the remove to delete it from the database first.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top