当我想保存我的对象时遇到这个问题
我的客户
String firstName
String lastName
LocalDate dateOfBirth
CountryCode nationality
我的国家/地区代码
@Audited
class CountryCode implements Serializable {
String code
String symbolA2
String symbolA3
String countryName
static constraints = {
code size:3..3, unique: true, matches: '[0-9]+'
symbolA2 size:2..2, nullable: false, unique: true, matches: '[A-Z]+'
symbolA3 size:3..3, nullable: false, unique: true, matches: '[A-Z]+'
countryName size:1..50
}
static mapping = {
id generator: 'assigned', name: 'code'
}
def beforeValidate() {
symbolA2 = symbolA2?.toUpperCase()
symbolA3 = symbolA3?.toUpperCase()
}
@Override
String toString() {
return countryName
}
}
当我尝试保存我的对象时,我收到此错误
Class org.hibernate.TransientObjectException Message object references an unsaved transient instance - save the transient instance before flushing: lookup.iso.CountryCode
您有解决此问题的想法吗?
谢谢
最佳答案
使用 Grails 关系约定
static hasOne = [nationality:CountryCode]
在客户类别和
static belongsTo = [customer:Customer]
在 CountryCode 类
检查grails docs关于这一点,特别是关于级联保存的段落。 如果这不适合您的情况,那么您需要在将 CountryCode 实例分配给 Customer 实例之前调用 save() 。
您还可以使用 static embedded 如果适用于您的情况。
如果您将 CountryCode 视为字典实体,则另一件事是从存储库加载所需的 ContryCode 实例,然后再将其分配给 Customer 实例。
关于Grails 对象引用未保存的 transient 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16034702/