spring - GRAILS-GORM:保存新对象期间出现DuplicateKeyException

标签 spring hibernate grails gorm

我使用GORM从Excel文件中备份数据库中的事件。

new ExcelBuilder(excelFile.inputStream).eachLine([labels: true, sheet: 0]) {
                if (cell(0)) {
                    def nameA = cell(0)
                    def nameB = cell(1)
                    def a = Chapitre.findByNom(nameA)

                def code = cell(2)
                def designation = cell(3)

                if (code == null || nameA == null || nameB == null) {
                    flash.messages << "error"
                } else if (!Chapitre.findByNom(nameA)) {
                    flash.messages << "error"
                } else if ( Rubrique.where{nom == nameB && chapitre == a}.list().size() == 0) {
                    flash.messages << "error"
                } else if(Object.where{rubrique == Rubrique.findByNom(nameB) && c == code && d == designation}.count() > 0){
                    flash.messages << "error"
                } else {

                        def b = Rubrique.findByNom(nameB)
                        def isNew = false;

                        Object.withNewSession {session2->
                            def object = Object.findOrCreateByCode(code)

                            if(object.designation == null)
                                isNew = true;

                            object.rubrique = b
                            object.d= (designation == null)?"":designation
//                              try {
                                    rowCount += object.save()? 1 : 0
//                              } catch(ValidationException) {
//                                    if(isNew)
//                                        rowCount++;
//                                    log.info("ErreuRRRRRRRRrrrRRrrRrRRrrrrRrrrRrrrRrrrr")
//                              }
                            }
                    }
                }
                currentLine++
}
flash.messages << "${rowCount} ligne create or update"

更新将消除任何后顾之忧,文件行的过程继续进行,数据库记录有效。

但是,当涉及到插入新对象时,出现异常:
org.springframework.dao.DuplicateKeyException: a different object with the same identifier value was already associated with the session:[fen.NuisanceType#2202]; 
nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

有问题的对象的注册是有效的,但是该错误引起了文件路径的错误。

当我取消注释trycatch时,我绕过了错误,因此每个文件的所有副本都在数据库中创建。

因此,我找到了解决问题的方法,但是我发现它并不是很干净,我来找您尝试理解我的问题。

最佳答案

没有更多信息,很难给出任何明确的答案。这段代码是否还存在于服务中?(这非常令人怀疑,因为它的flash.message指向 Controller 完成了所有工作。)尝试使其成为服务并具有事务性,然后您可以考虑使用withNewTransaction调用删除它。

您可以在此处阅读有关创建的错误的更多信息:
Grails - DuplicateKeyException
评论评论:
“好吧,当您手动初始化具有id或unique属性的新ClassD类时,当 session 中已经存在另一个类时,就会发生此问题。因此,您应该尝试首先获取该实体(这就是findOrCreateWhere所做的,但是如果您使用您需要使用get的ID),然后使用找到的实例或为更新创建一个新实例”

Hibernate Error: a different object with the same identifier value was already associated with the session

您整理过的代码并从服务运行:(问题可能会消失),因为我还清理了您正在执行的重复发现:

class TestService {

    static transactional=true

    def saveRecord()  {
        def results=[]
        new ExcelBuilder(excelFile.inputStream).eachLine([labels: true, sheet: 0]) {
            if (cell(0)) {
                def nameA = cell(0)
                def nameB = cell(1)
                def code = cell(2)
                def designation = cell(3)

                def a = Chapitre.findByNom(nameA)
                def b = Rubrique.where{nom == nameB && chapitre == a}
                def c = Object.where{rubrique == b && c == code && d == designation}

                if (!code||!nameA||!nameB||!a||!b||!c) {
                    results << "Error saving ${nameA} ${nameB} ${code}"
                } else {
                    //boolean isNew = false
                    def object = Object.findOrSaveWhere(code:code)
                    if(object) { 
                        if (!object.designation) {
                            rowCount++
                            results << "Record ${object} has no designation ? new Record?"
                        }
                        object.rubrique = b
                        object.d = designation ?: ''
                        object.save()
                        results << "Record ${object.id} is saved"
                    } else {
                        /*
                         *  Could not save or find code:code now create a new object:
                         *  object = new Object(code:code, rubrique:rubrique: d: designation ?: '').save()
                         *  
                         */
                    }   
                }
            }
            currentLine++
        }
        results <<  "${rowCount} ligne create or update"
        return results
    }
}

关于spring - GRAILS-GORM:保存新对象期间出现DuplicateKeyException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33232935/

相关文章:

java - Hibernate IN/ANY 与 Criteria 中的自定义转换器

java - Hibernate 搜索 - '%like%' 类型查询

java - 访问 Controller 中的特定 Grails 参数

hibernate - 如何在Grails 3中覆盖DomainClass getter

spring - JMeter、JUnit 和 Spring Java 配置

spring - org.springframework.beans.factory.BeanCurrentlyInCreationException : Error creating bean with name 'sessionFactory'

spring - Spring Data JPA 是 JPA 实现吗?

java - 当表已经创建时,设置长度在 hibernate 中不起作用

java - Spring 4、MyBatis、带注解的多数据源

java - Tomcat 服务器部署连接关闭