Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

like image 376
David Tinker Avatar asked Nov 29 '11 11:11

David Tinker


2 Answers

You need to get to the Hibernate session and persistence context:

import org.hibernate.engine.Status

boolean deleted = Project.withSession { session ->
   session.persistenceContext.getEntry(p).status == Status.DELETED
}
like image 130
Burt Beckwith Avatar answered Nov 19 '22 02:11

Burt Beckwith


You could use GORM events to automatically set a property within the object once it has been deleted, e.g.

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:

if (Project.exists(p.id)) {
  // do something....
}
like image 44
Dónal Avatar answered Nov 19 '22 03:11

Dónal