【问题标题】:Grails / GORM : org.hibernate.AssertionFailure: null id in xyz (don't flush the Session after an exception occurs)Grails / GORM : org.hibernate.AssertionFailure: xyz 中的空 id (发生异常后不要刷新会话)
【发布时间】:2023-04-07 20:19:01
【问题描述】:

编辑:得到-1,你能解释一下原因吗?我搜索了重复项,但没有找到。

针对我刚刚遇到的问题发布 Q/A:

class Pineapple {
    def pineappleService

    Supplier supplier;

    def beforeInsert() {
        pineappleService.beforeInsert(this);
    }
}

class PineappleService {
    def beforeInsert(Pineapple pineapple) {
         Pineapple.withNewSession {
             // some logic
             pineapple.supplier.save();
         }
    }
}

例外:

org.hibernate.AssertionFailure: xyz 中的null id(发生异常后不要刷新Session)

【问题讨论】:

    标签: hibernate grails grails-orm


    【解决方案1】:

    诀窍是将闭包移动到域类:

    class Pineapple {
        def pineappleService
    
        Supplier supplier;
    
        def beforeInsert() {
            Pineapple.withNewSession {
                pineappleService.beforeInsert(this);
            }
        }
    }
    
    class PineappleService {
        def beforeInsert(Pineapple pineapple) {
             // some logic
             pineapple.supplier.save();
        }
    }
    

    文档:

    注意上面 withNewSession 方法的使用。由于事件是 在 Hibernate 使用持久性方法刷新时触发,例如 save() 和 delete() 不会导致对象被保存,除非你运行 使用新 Session 进行操作。

    幸运的是 withNewSession 方法可以让你共享相同的 即使您使用的是不同的事务 JDBC 连接 底层会话。

    【讨论】:

      猜你喜欢
      • 2016-06-17
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 2014-01-26
      • 1970-01-01
      • 2011-07-15
      • 2012-01-28
      相关资源
      最近更新 更多