I have 2 domain classes as follows -
class A {
static hasMany = [B] // Just trying to show my mapping
}
class B {
// This table doesn't belongs to A
}
Now I have a object of class A which contains a set of objects B. I want to delete object A and its association with B, but I don't want to delete object B.
I have tried cascade for delete, delete-all & delete-all-orphan but it seems to be trying to delete the associated records from table B which isn't what I want.
This is what I am doing right now -
objectTypeB.each { b ->
a.removeFromB(b)
}
and then
a.delete()
but getting error
deleted object would be re-saved by cascade (remove deleted object from associations)
Your example is almost correct, I think what you need is tell A what collection to store B's in (see the hasMany)
class A {
String name
static hasMany = [b: B]
}
class B {
String name
}
Then it should be possible to do this (I tried it in a blank project, where my domains also have a String name property):
def b1 = new B(name: 'b1').save(flush: true)
def b2 = new B(name: 'b2').save(flush: true)
def b3 = new B(name: 'b3').save(flush: true)
def a = new A(name: 'a')
a.addToB(b1)
a.addToB(b2)
a.save(flush: true)
def x = A.get(1)
println x.b
x.delete(flush: true)
assert A.count() == 0
Since there is no relation from B to A, there is no need to remove the b's from A before deleting the A. If you want, I can send you my code sniplet