【问题标题】:alternative to grails multicolumn unique constraint (optimistic inserts)替代 grails 多列唯一约束(乐观插入)
【发布时间】:2015-03-19 15:08:43
【问题描述】:

我有一个重度使用的域类Relationship,它看起来与下面的非常相似

class Relationship {
    Element source
    Element destination
    Type type

    // other properties omitted

    static constraints = {
         type unique: ['source', 'destination']
    }
}

我有一个服务创建这个域类的新实例,它检查现有实例,如果发现重用它们,但我想只在数据库中实现具有唯一约束的乐观插入,因为

  1. GORM 唯一约束非常低效(对于一个简单的任务,我仅检查约束就获得了 13000 次点击,并且花费了三分之一的时间)
  2. 批量运行时查找现有实体的成本很高(每个查询都会刷新当前会话,花费大约 40 毫秒)

所以想法是让save 方法失败,然后重用现有实体

try {
    relationshipInstance.save()
} catch (DataIntegrityViolationException | ConstraintViolationException e) {
    // find and reuse
}

但是当我尝试查找实体时,我得到了休眠异常

AssertionFailure: null id in Relationship entry (don't flush the Session after an exception occurs)
  1. 有什么方法可以从异常中恢复(relationshipInstance.discard() 没有帮助,因为它没有 EntityKey)?
  2. 对于不触发刷新的按需唯一性检查,您还推荐什么其他解决方案?

【问题讨论】:

    标签: hibernate grails grails-orm


    【解决方案1】:

    您可以在调用 save 时禁用验证,如下所示:

    relationshipInstance.save(validate:false)
    

    请参阅documentation for save method 了解更多信息。

    【讨论】:

    • 谢谢,但这可能不是我想要的。这将出现同样的问题,因为您无法使用此表示法禁用数据库约束。
    • 如果你有大量的数据需要加载到数据库中,我建议直接使用JDBC。 Gorm/Hibernate 对于大容量的性能相当差。如果你还想使用 Gorm,最好在事务外创建一个结构体中的所有对象,然后在事务内一次性保存。
    猜你喜欢
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多