删除项目后,hasMany 关联列表中为空 [英] Null in hasMany assosiation list after removing item

查看:19
本文介绍了删除项目后,hasMany 关联列表中为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有域对象:

 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()

看起来,GORM 没有更新关联表中的 idx 字段.我无法重现它,但我在生产服务器上得到了几次

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玛丽亚数据库

Grails 2.4.5 MariaDB

推荐答案

我认为问题可能取决于您在类上设置的级联删除行为.首先,调用后

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()

你必须打电话.

pic.delete()

但如果问题仍然存在,您可以使用 GORM 事件,以便在您的类中添加:

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)
}

参考:GORM 活动

这篇关于删除项目后,hasMany 关联列表中为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆