Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: check whether an entity object has been persisted or not

Is there a general method that can

 if(entity is persisted before){
     entity = entity.merge();
 }else{
     entity.persist();
 }

So the method contain above logic is safe everywhere?

like image 694
Dreamer Avatar asked Apr 18 '13 20:04

Dreamer


1 Answers

If you need to know is object already in persistence context you should use contains method of EntityManager.

Only EntityManager can tell you is entity persisted or not, entity does not have such information.

Here you can check javadoc for contains method.

if (!em.contains(entity)) {
  em.persist(entity);
} else {
  em.merge(entity);
}
like image 135
IgorMadjeric Avatar answered Nov 14 '22 01:11

IgorMadjeric