Hibernate grails多列唯一约束的替代方案(乐观插入)

Hibernate grails多列唯一约束的替代方案(乐观插入),hibernate,grails,gorm,Hibernate,Grails,Gorm,我有一个频繁使用的域类关系,它看起来非常类似于下面的一个 class Relationship { Element source Element destination Type type // other properties omitted static constraints = { type unique: ['source', 'destination'] } } 我有一个创建这个域类的新实例的服务,该服务检查现有

我有一个频繁使用的域类
关系
,它看起来非常类似于下面的一个

class Relationship {
    Element source
    Element destination
    Type type

    // other properties omitted

    static constraints = {
         type unique: ['source', 'destination']
    }
}
我有一个创建这个域类的新实例的服务,该服务检查现有实例,如果发现,则重用它们,但我希望只在数据库中使用唯一约束实现某种乐观插入,因为

  • GORM独特约束的效率非常低(对于一个简单的任务,我只需检查约束和花费的三分之一时间,就获得了13000次点击)
  • 批量运行时查找现有实体的成本很高(每个查询刷新当前会话,花费约40毫秒)
  • 因此,我们的想法是让
    save
    方法失败,而不是重用现有实体

    try {
        relationshipInstance.save()
    } catch (DataIntegrityViolationException | ConstraintViolationException e) {
        // find and reuse
    }
    
    但当我试图找到实体时,我得到了hibernate异常

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

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

    relationshipInstance.save(validate:false)
    

    有关更多信息,请参阅

    谢谢,但那可能不是我想要的。这与不能使用此符号禁用数据库约束的情况相同。如果需要将大量数据加载到数据库中,我建议直接使用JDBC。Gorm/Hibernate在大容量情况下的性能相当差。如果仍要使用Gorm,最好在事务外部的结构中创建所有对象,然后在事务内一次性保存它们。