2013-04-16 33 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實例也是另一回事。

相關問題