Search code examples
hibernategrailsgrails-orm

Null in hasMany assosiation list after removing item


There is domain object:

 class Book {
      List<Picture> pictures
      static hasMany = [pictures:Picture]
      static mapping = {
        pictures lazy: false, cache: 'nonstrict-read-write'
      }
    }

Sometimes, after deleting pictures from list by code it produce null item in pictures list.

..
book.refresh()
def pic = Picture.get(params.id)
subject.removeFromPictures(pic)
subject.save()

It looks like, GORM not update idx field in assosiation table. I can't reproduce it, but I got few times it on production server

In my opinion, it can be problem of second level cache and concurent modification. How to prevent it?

Grails 2.4.5 MariaDB


Solution

  • i think the problem can depend on the cascade delete behaviour you set on the class. First of all, after calling

    subject.removeFromPictures(pic)
    subject.save()
    

    You have to call.

    pic.delete()
    

    But if the problem persist, you can use GORM events so in your class you can add:

    class Book {
    ...
    ...
    def beforeUpdate(){
    checkNulls()
    }
    
    def beforeValidate(){
    checkNulls()
    }
    
    def checkNulls(){
    pictures?.removeAll(null)
    }
    

    Ref: GORM Events