Grails 添加到*不设置回引用
我有两个具有一对多关系的域类:Grails 添加到*不设置回引用,grails,gorm,Grails,Gorm,我有两个具有一对多关系的域类: class DataType { Integer id ... static hasMany = [dataTypeProps: DataTypeProp] } class DataTypeProp implements Serializable { String name String value static belongsTo = [dataType: DataType] int hashCod
class DataType {
Integer id
...
static hasMany = [dataTypeProps: DataTypeProp]
}
class DataTypeProp implements Serializable {
String name
String value
static belongsTo = [dataType: DataType]
int hashCode() {
def builder = new HashCodeBuilder()
builder.append dataType.id
builder.append name
builder.toHashCode()
}
}
然后我创建一个新的数据类型实例,并向其添加一个属性,如下所示:
new DataType().
addToDataTypeProps(name: 'test name', value: 'test value')
.save()
我得到一个NullPointerException,因为尚未设置对数据类型的反向引用
java.lang.NullPointerException: Cannot get property 'id' on null object
at de.marketmaker.dm.treasury.model.DataTypeProp.hashCode(DataTypeProp.groovy:13)
at java_util_Set$add$2.call(Unknown Source)
at Script1$_run_closure1$_closure3$_closure4.doCall(Script1.groovy:22)
Gorm文档说,back引用是由addTo*方法设置的。但问题是为什么它调用得太晚以至于导致异常。我只是做了同样的设置,没有问题!我想有两件事你应该试试
new DataType(
dataTypeProps: [
new DataTypeProp(name: 'test name1', value: 'test value1'),
new DataTypeProp(name: 'test name2', value: 'test value2')
]
).save()
1将属性名称id更改为其他名称,GORM将免费提供其中一个。以及
2投诉是显而易见的,向尚未在数据库中解决的父对象添加子对象。因此,声明并保存父对象,然后按照现有方式将子对象添加到hasMany属性中。您不能得到空值。当您尝试DataTypeProps dataProp=new DataTypePropsname:'test',value:'test value';dataProp.save;是否新建DataType.addToDataTypePropsdataProp.save?另外,您使用的是什么版本的Grails?在字段“dataType”上的对象“DataTypeProp”中出现-Field错误:拒绝值[null];例外我使用的是2.5.0版本,在添加子项之前不必保存父项-这是GORM更酷的特性之一。保存外部对象会导致级联验证并保存内部对象。我的印象完全正确,这就是为什么我尝试了设置,自己没有问题。我只是在回答NPE报告的问题。