如何判断当前tx(Hibernate)中是否删除了Grails / GORM域实例?

时间:2011-11-29 11:06:51

标签: java hibernate grails gorm

我正在为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 个答案:

答案 0 :(得分:6)

您需要进入Hibernate会话和持久化上下文:

import org.hibernate.engine.Status

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

答案 1 :(得分:1)

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

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

  def afterDelete() { 
   isDeleted = true
  }
}

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

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

答案 2 :(得分:0)

我的想法:

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