Service access in beforeDelete ()

I want to call a service inside my grails beforeDelete () domain objects. Unfortunately, it always works reproducibly when an event is triggered. I built an example that reproduces the problem. Domain Object:

class Gallery { def myService def beforeDelete() { // System.out.println(myService); // not even this works, same error! System.out.println(myService.say()); } } 

Service:

 class MyService { String say() { "hello" } } 

Testing Controller:

 class DeleteController { def index() { Gallery.list().each { it.delete() } } def create() { def gallery = new Gallery() gallery.save() } } 

If I run the application and call create followed by an index, I get:

 Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [testbeforedelete.Gallery#1] 

I want to make a call that is a little more complicated than this example. I can’t explain this behavior, and I don’t know how to handle it. I know that Hibernate events need special care, but I'm stuck.

+4
source share
1 answer

The beforeDelete function actually makes changes to your domain class. I agree that you do not expect this behavior. Hibernate believes that you are modifying an instance. You can use the following code to get around your problem.

 def beforeDelete() { Gallery.withNewSession { System.out.println(myService.say()); } } 
+5
source

All Articles