如何判断在当前事务(Hibernate)中Grails/GORM领域实例是否已被删除?

5
我正在寻找一个适用于Grails(GORM)实例的"isDeleted()"测试:

Project p = ... get persistent entity from somewhere ...
p.delete() // done in some nested logic
... sometime later in the code prior to commit of the tx ...
if (!p.isDeleted()) ... do some more stuff ...

在我的应用中,可能删除 p 标签的逻辑在其他地方,传递标志返回或其他操作会很繁琐。
3个回答

6

您需要获取到Hibernate会话和持久化上下文:

import org.hibernate.engine.Status

boolean deleted = Project.withSession { session ->
   session.persistenceContext.getEntry(p).status == Status.DELETED
}

我在org.hibernate.Session上找不到getPersistenceContext()方法? - David Tinker
org.hibernate.impl.SessionImpl 实现的是 org.hibernate.engine.SessionImplementor 接口。 - Burt Beckwith
最终我使用了 boolean deleted = Project.withSession { session -> session.persistenceContext.getEntry(p)?.status in [null, Status.DELETED] },因为该实体对于我来说不在会话中 - 可能是因为它已经使用 flush: true 删除了。 - Chris Peacock

1

您可以使用GORM事件在对象被删除后自动设置属性,例如:

class Project{
   String name
   Boolean isDeleted = false
   static transients = [ "isDeleted" ]

  def afterDelete() { 
   isDeleted = true
  }
}

如果出于某些原因您不想修改域类,您可以使用exists方法:

if (Project.exists(p.id)) {
  // do something....
}

0

我的想法:

Project p = ... 
def id = p.id
p.delete(flush:true)
...
if (p.read(id)) //... do some more stuff ...

当我使用get/read时,我遇到了org.hibernate.ObjectNotFoundException嵌套在HibernateObjectRetrievalFailureException中。我正在使用Grails 2.0RC1,所以可能是一个bug。 - David Tinker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接