java JPA:检查实体对象是否已持久化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16092008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:53:14  来源:igfitidea点击:

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

javajakarta-eejpaejb

提问by Dreamer

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?

那么包含上述逻辑的方法在任何地方都是安全的?

回答by IgorMadjeric

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

如果你需要知道的是对象已经在你应该使用持久化上下文contains的方法EntityManager

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

只能EntityManager告诉你实体是否持久化,实体没有这些信息。

Here you can check javadoc for containsmethod.

在这里您可以检查 javadoc 以获取contains方法

if (!em.contains(entity)) {
  em.persist(entity);
} else {
  em.merge(entity);
}

回答by Khalil

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

要检查当前 PersistenceContext 是否已持久化实体对象,您可以使用 EntityManager 方法contains(Object entity)