demon101
demon101

Reputation: 564

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

Upvotes: 4

Views: 228

Answers (1)

Giuseppe Iacobucci
Giuseppe Iacobucci

Reputation: 423

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

Upvotes: 1

Related Questions