2013-04-16 37 views
3

我有这个问题,当我要救我的对象Grails的对象引用一个未保存的瞬态的实例

我的客户

String firstName 
String lastName 
LocalDate dateOfBirth 
CountryCode nationality 

我COUNTRYCODE

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

当我尝试保存我的对象我收到这个错误

类 只org.hibernate.TransientObjectException 消息 对象引用一个未保存的瞬态的实例 - 冲洗之前保存的瞬态的实例:lookup.iso.CountryCode

你有想法如何解决这一问题?

Thankx

+0

当您实际执行保存时,您可以添加代码的相关部分吗? – lucke84

回答

2

的具体原因你的错误是因为你还没有将其分配给客户之前保存的COUNTRYCODE,因为Hibernate(Grails的底层ORM)认为短暂的。基本上你没有任何GORM关系(例如has *,belongsTo)定义。通过定义GORM关系,您可以根据关系的定义获得级联保存/删除的功能。

在简单地将hasOne或belongsTo分别添加到Customer和CountryCode之前,您可能需要考虑如何使用CountryCode。被COUNTRYCODE用作:

  1. 一个一对多的查找/参考/字典,许多客户可能会被映射到特定COUNTRYCODE实体
  2. 一到一个独特的实体,那里的每个客户
  3. 独特的COUNTRYCODE

要实现#1,你应该在COUNTRYCODE 定义使用belongsTo只是一个单向的关系WITHOUT客户一个hasOne像这样:

class CountryCode { 
    static belongsTo = [customer: Customer] 
    ... 
} 

这将在引用特定CountryCode的Customer表上创建一个外键 - 基本上是一对多的。

为了实现#2,您应当在客户中COUNTRYCODE 定义使用belongsTo双向关系与一个hasOne像这样:

class Customer { 
    static hasOne = [country: CountryCode] 
    .. 
} 
class CountryCode { 
    static belongsTo = [customer: Customer] 
    .. 
} 

这将创建在COUNTRYCODE表的外键回一个特定的客户 - 基本上是一对一的映射。

+0

这是一个很好的解释和解决方案,问题出现的时候不是必需的关系,在我的情况下,'国家代码'可以或不可以。 – Neoecos

2

使用Grails的关系公约

static hasOne = [nationality:CountryCode] 

在Customer类和

static belongsTo = [customer:Customer] 

在COUNTRYCODE类

检查grails docs有关,特别是段落说明有关级联扑救。 如果这不适合您的情况,则需要在将CountryCode实例分配给Customer实例之前调用save()方法。

您也可以使用static embedded如果适用于您的情况。

如果您将CountryCode作为字典实体考虑,那么在将其分配给Customer实例之前,从存储库加载所需的ContryCode实例也是另一回事。

相关问题