我尝试在grails服务中将对象保存在mongodb中:
Cover saveCover = new Cover()
saveCover.id = url
saveCover.url = url
saveCover.name = name
saveCover.sku = sku
saveCover.price = price
saveCover.save()
Cover域如下所示:
class Cover {
String id
String name
String url
String sku
String price
}
所以我想有基于URL的自定义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
但是我没有使用setter,只是在构造函数中传递了所有值,所以这个异常消失了。为什么?
最佳答案
如此处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'
}
并将使用insert方法,您将获得一个自动生成的objectId:
"_id" : "5496e904e4b03b155725ebdb"
关于mongodb - Grails Gorm + mongoDb在保存期间获取OptimisticLockingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19504238/