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

馋奶兔 提交于 2019-12-22 03:40:33

问题


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?


回答1:


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);
}



回答2:


To check if entity object has been persisted or not by the current PersistenceContext you can use the EntityManager method contains(Object entity)



来源:https://stackoverflow.com/questions/16092008/jpa-check-whether-an-entity-object-has-been-persisted-or-not

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!