mongodb - Grails Gorm + mongoDb在保存期间获取OptimisticLockingException

标签 mongodb grails gorm

我尝试在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/

相关文章:

mongodb - 多条件获取 MongoDB 集合记录

grails - Groovy/Grails工具套件中的Web应用程序重新加载问题

grails - 正则表达式验证-Grails约束

grails - Grails,旧版数据库无法获取正确的ID类型

node.js - 洞察两种 REST API 设计的可行性

mongodb - 边写边转储

grails - 如何将使用探查器的grails日志追加到自​​定义追加程序(日志文件)中?

grails - 如何从grails应用程序访问日志目录中的文件?

multithreading - Grails:如何在异步Web请求后将对象保存到DB?

python - 如何使用 Python 从 MongoDB 中的此文档中删除值