0

I'm trying to understand GORM's cascaded deletion. That is default GORM behavior without any modifiers. I understand that if an owning instance of domain class Owner owns several instances of an Owned domain class, then when the Owner instance is deleted, all the owned instances will be deleted as well. But what if the owned instances were owned simultaneously by two different Owners and only one Owner were deleted. Would the owned instances then not be deleted because they are still owned by the other not deleted Owner?

EDIT: I actually tried to perform the experiment (at least the first part of it) but I did not achieve the expected results. Being a newbie, I'm quite sure I'm doing something wrong. Just don't know what.

class MainController {

    def index() {
        // creating a few instances of the owned domain class
        def owneda = new Owned(name: 'Owned A')
        def ownedb = new Owned(name: 'Owned B')
        def ownedc = new Owned(name: 'Owned C')

        // now we make these instances belong to an instance of OwnerA
        // first we create an instance of OwnerA
        def ownerA = new OwnerA(name: 'Owner A')

        // then we give it ownership of all the instances of Owned that we created
        ownerA.addToOwned(owneda)
        ownerA.addToOwned(ownedb)
        ownerA.addToOwned(ownedc)

        // now we save the owner instance
        ownerA.save(flush: true)

        // now we see how many instances of both Owners and Owned are in our db
        println "The number of Owner As in existence are: " + OwnerA.count()
        println "The number of Owned in existence are: " + Owned.count()

        // Now we delete the owner instance
        ownerA.delete(flush: true)

        // now we see how many instances of both Owners and Owned are in our db after the deletion
        println "After deletion of the OwnerA instance..."
        println "The number of Owner As in existence are: " + OwnerA.count()
        println "The number of Owned in existence are: " + Owned.count()
    }
}

I did put the belongsTo in my Owned class and the hasMany in my Owner class.

output:

...........The number of Owner As in existence are: 0
The number of Owned in existence are: 0
After deletion of the OwnerA instance...
The number of Owner As in existence are: 0
The number of Owned in existence are: 0
Anonymous Human
  • 1,858
  • 1
  • 21
  • 47

1 Answers1

1

Hibernate does not support "ON DELETE SET NULL" for cascading. So if your owned object is owned by multiple owners, if you delete one of the owner the owned object wont be deleted.

You will most likely get "InvalidDataAccessApiUsageException: deleted object would be re-saved by cascade" or FK constraint violation exception

See this similar question

Community
  • 1
  • 1
Sudhir N
  • 4,008
  • 1
  • 22
  • 32