Grails 将域对象添加到gorm关系获取空指针异常

Grails 将域对象添加到gorm关系获取空指针异常,grails,gorm,Grails,Gorm,以下是我的域类定义: class Profile { PhotoAlbum photoAlbum static constraints = { photoAlbum(nullable:true) } } class PhotoAlbum { static hasMany = [photos:Photo] static belongsTo = [profile:Pr

以下是我的域类定义:

class Profile {
           PhotoAlbum photoAlbum

           static constraints = {
               photoAlbum(nullable:true)
           }
}

class PhotoAlbum {

        static hasMany = [photos:Photo]
        static belongsTo = [profile:Profile]

}

class Photo {
       static belongsTo = PhotoAlbum
}
在控制器中,我将有一个实例化的概要文件域。域以空相册开始。如果我想添加第一张照片,我会在相册上得到一个空指针异常:

Photo photo = new Photo()

profile.photoAlbum.addToPhotos(photo)
实现这一点并避免空指针异常的grailsy方法是什么:

Photo photo = new Photo()

if (!profile.photoAlbum) { profile.photoAlbum = new PhotoAlbum) }

profile.photoAlbum.addToPhotos(photo)

我本以为如果photoAlbum为null,grails会在尝试向其添加第一个photo对象时创建一个新对象。虽然上面的3行代码可以工作,但我想知道是否有更好的方法可以在2行代码中完成同样的任务。

您可以在
配置文件中覆盖
PhotoAlbum
的getter来按需创建相册:

class Profile {
    ...
    PhotoAlbum getPhotoAlbum() {
        if (photoAlbum == null) {
            photoAlbum = new PhotoAlbum()
        }
        photoAlbum
    }
}
然后,当您调用
profile.photoAlbum
时,它将按照您的预期自动创建。不过,无论何时调用getter,这都会创建空相册,这可能不是您想要的。我想说得更清楚一些,比如:

class Profile {
    ...
    PhotoAlbum createOrGetPhotoAlbum() {
        if (photoAlbum == null) {
            photoAlbum = new PhotoAlbum()
        }
        photoAlbum
    }
}

这样称呼它:
profile.createOrGetPhotoAlbum().addToPhotos(photo)

你做得很好,伊姆霍。任何非托管集合(hasMany)的属性如果以null开头,则在将其设置为非null之前都将为null。Grails/Groovy不能仅仅因为您的代码试图在null对象上设置属性,就假定您希望它为您实例化它。很好,很干净。在您需要查找带有空PhotoAlbum的配置文件之前,这可能是一个问题,因为它将始终返回not-null。第二种方法使创建显式并避免该问题。