【问题标题】:E11000 duplicate key error index - Grails afterInsert() methodE11000 重复键错误索引 - Grails afterInsert() 方法
【发布时间】:2015-10-28 20:43:20
【问题描述】:

我遇到了这个奇怪的错误,无法找到任何解决方案,我认为这是我的案例的其他问题。

我在这样的域中的afterInsert() 方法中遇到了这个问题

Class Employee {
    /** other code **/

    def afterInsert() {
        println "Inserting..."
        if (!hasAfterInsert) {
            hasAfterInsert = true
            DatabaseEvent.withTransaction { status ->
                def dbEvent = new DatabaseEvent(loggedInUser: null,
                        type: "Created", entityClass: this.getClass().getName(), eventObjectId: this.id)
                dbEvent.save(failOnError: true)
            }
        }
    }
}

插入新员工后,我正在使用此方法创建记录,但是当我在 afterInsert() 中有此代码时,这会引发此错误。

我的DatabaseEvent 类是这样的

class DatabaseEvent {

    ObjectId id
    String type
    String entityClass
    String eventObjectId
    Date dateCreated
    User loggedInUser
}

这给出了类似的东西:

E11000 duplicate key error index: myApp.Employee.$_id_ dup key: { : ObjectId('5631313fe4b0bbeba418859b') }

我不明白为什么在我将 DatabaseEvent 对象保存到 afterInsert() 时会发生这种情况??

【问题讨论】:

    标签: mongodb grails


    【解决方案1】:

    因此,当您保存 Employee 的新实例时,您的 GORM 会话尚未刷新,这意味着您的新 Employee 实例仍在 GORM 会话中,而您的新 Employee 实例有一个新的 @987654325 @即ObjectId('5631313fe4b0bbeba418859b').

    现在在您的afterInsert() 方法中,您正在使用相同的事务来保存DatabaseEvent 的新实例。在保存DatabaseEvent 的新实例时,GORM 将再次刷新相同的 GORM 会话,并且最近创建的Employee 实例再次尝试使用相同的idObjectId('5631313fe4b0bbeba418859b') 进行保存,这会导致重复键错误.

    因此,只需将 afterInsert() 方法中的代码更改为使用 withNewSession 而不是 withTransaction 闭包,这应该可以工作。

    【讨论】:

    猜你喜欢
    • 2017-03-02
    • 2019-07-11
    • 2016-10-31
    • 1970-01-01
    • 2017-01-03
    • 2014-01-06
    • 1970-01-01
    • 2018-01-19
    相关资源
    最近更新 更多