2013-10-21 32 views
0

我嘗試在Grails的服務保存對象MongoDB中:Grails的格羅姆+ MongoDB中得到

Cover saveCover = new Cover() 
saveCover.id = url 
saveCover.url = url 
saveCover.name = name 
saveCover.sku = sku 
saveCover.price = price 

saveCover.save() 

封面域看起來是這樣的:

class Cover { 

    String id 
    String name 
    String url 
    String sku 
    String price 
} 

所以我想有自定義ID基於網址,但在保存過程中我得到錯誤:

Could not commit Datastore transaction; nested exception is org.grails.datastore.mapping.core.OptimisticLockingException: The instance was updated by another user while you were editing

但我沒有使用setters,只是通過所有值在構造函數中,這個異常消失了。爲什麼?

回答

2

據報道在documentation這裏:

Note that if you manually assign an identifier, then you will need to use the insert method instead of the save method, otherwise GORM can't work out whether you are trying to achieve an insert or an update

,所以你需要使用插入方法而不是當ID發生器是

cover.insert(failOnError: true) 

保存,如果你不這樣定義的映射:

static mapping = { 
    id generator: 'assigned' 
} 

並將使用插入方法,你會得到一個自動生成的objectId:

"_id" : "5496e904e4b03b155725ebdb" 
1

當您爲新模型分配一個id並嘗試保存它時發生此異常,因爲GORM認爲它應該進行更新。

爲什麼當我遇到了這個問題,我用的是Grails的 - 蒙戈插件的1.3.0這個例外時

。這使用1.1.9的Grails數據存儲核心代碼。我注意到在847(ish) of NativeEntryEntityPersister行產生異常。此代碼更新數據庫中的現有域對象。

Above that on line 790是其中isUpdate被創建用於查看它是否是更新。 isInsertfalse,因爲只有在插入被強制時true,並且readObjectIdentifier將返回已分配給該對象的標識,因此isUpdate將最終評估爲true。

修復異常

由於&& !isInsert上線791,如果你強行插入插入代碼將調用果然異常會消失。但是,當我這樣做時,分配的ID沒有保存,而是使用了生成的對象ID。我看到這個問題的解決方案在line 803,它檢查發生器是否設置爲"assigned"

要解決您可以添加以下映射。

class Cover { 
    String id 
    String name 
    String url 
    String sku 
    String price 
    static mapping = { 
     id generator: 'assigned' 
    } 
} 

這樣做的副作用是,你永遠需要分配新蓋的域對象的ID。

+0

我不明白GORM默認爲什麼這麼認爲。你能解釋一下嗎? – sphinks

+0

我已經更新了關於爲什麼gorm認爲這個更詳細的問題。 – PaddyDwyer