简体   繁体   English

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

[英]How can I tell if a Grails/GORM domain instance has been deleted in the current tx (Hibernate)?

I am looking for a "isDeleted()" test for Grails (GORM) instances: 我正在寻找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 ...

In my app the logic that may delete p is elsewhere and passing a flag back or something would be a pain. 在我的应用程序中,可能删除p的逻辑在其他地方并且传回一个标志或某些东西会很痛苦。

You need to get to the Hibernate session and persistence context: 您需要进入Hibernate会话和持久化上下文:

import org.hibernate.engine.Status

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

You could use GORM events to automatically set a property within the object once it has been deleted, eg 您可以使用GORM事件在删除对象后自动设置属性,例如

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

  def afterDelete() { 
   isDeleted = true
  }
}

If for some reason you don't want to modify the domain classes, you could just use the exists method: 如果由于某种原因您不想修改域类,则可以使用exists方法:

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

my thoughts: 我的想法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何确保已删除 Kafka 主题? - How can I make sure that a Kafka topic has been deleted? 如何判断其他课程何时更新? - How can I tell when another class has been updated? Grails / GORM 2.3 Hibernate寻找抽象域类的持久化表 - Grails/GORM 2.3 Hibernate looking for abstract domain class persisted table Grails:用休眠类替换GORM - Grails:Replacing GORM with Hibernate class 在这种情况下,我如何通知适配器数据已被更改/删除 - how can i notify the adapter that data has been changed/deleted in THIS scenario 在finally块中,我能否说出抛出了什么异常? - In a finally block, can I tell what exception has been thrown? 我可以判断是否调用了抽象方法吗? - Can I tell if an abstract method has been called? 如何判断某个视图(平铺)是否已在Controller中定义? - How can I tell if a certain view (tile) has been defined in a Controller? 如何确定Play商店中的APK更新时间? - How can I tell when my apk has been updated in the Play store? 如何通过AWS Java API知道何时创建了EBS快照? - From the AWS Java API, how can I tell when my EBS Snapshot has been created?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM