1
votes

I have this 2 methods in the same service class:

boolean meth1(DomClass dom1) { //parameter is an instance of domain class DomClass
    ...
    meth2(dom1)
    ...
    dom1.delete(flush: true)
    ... 
    return true
}

boolean meth2(DomClass dom1) {
   ...
   dom1.changeSomeProperty
   dom1.save(flush:true)
   return true
}

The problem is that on the line calling dom1.delete(flush: true) the program crashes with deleted object would be re-saved by cascade (remove deleted object from associations).

Now, I don't know Hibernate very well, but my guess is that either method is creating a new transaction, and meth1 has the first transaction, and meth2 the second one. And indeed, if I remove the dom1.save everything works well.

Now, my question: I can make the meth1 to contain all the code from meth2, but this will mean that I duplicate code a lot (in my real example I want to reuse some logic in many places). How can I reuse the code on one method by making all the services methods stack run in the same transaction (if this is really the problem, else: "what is the problem?")

1
lets see the domain mapping for dom1 and any other classes that reference it.hvgotcodes

1 Answers

1
votes

that error happens when an instance of ClassA is referenced by an instance of ClassB, and the cascade settings of B would cause instances of A to be saved, and you delete the instance of A. The fix is simple, do exactly what the exception says and remove classA from whichever domain class references it.

So in your case dom1 is referenced by another object in the hibernate session. You need to go thru your domain model and figure out what the association is, and then remove dom1 from the other instance.

The reason removing the save call makes the code appear to work is because without the save, you are probably not saving the other instance that is accessing dom1 and causing the error to begin with. Without that instance being saved, there is no cascade.

Unless you are configuration transactions yourself, all service method invocations that occur within the first service method invocation should be using the same transaction. All service methods participate in the same transaction unless you explicitly write code to not do it that way. There might be something in the ... you posted.