How to determine if a Grails / GORM domain instance has been deleted in the current tx (Hibernate)?

I am looking for the isDeleted () test for instances of Grails (GORM):

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 application, the logic that can remove p is in a different place and passes the flag back or something hurts.

+5
source share
3 answers

You need to go into the Hibernate session and persistence context:

import org.hibernate.engine.Status

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

You can use GORM events to automatically set a property in an object after it is deleted, for example

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

  def afterDelete() { 
   isDeleted = true
  }
}

If for some reason you do not want to change the domain classes, you can simply use the method exists:

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

:

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

All Articles