【发布时间】:2015-03-19 15:08:43
【问题描述】:
我有一个重度使用的域类Relationship,它看起来与下面的非常相似
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
}
但是当我尝试查找实体时,我得到了休眠异常
AssertionFailure: null id in Relationship entry (don't flush the Session after an exception occurs)
- 有什么方法可以从异常中恢复(
relationshipInstance.discard()没有帮助,因为它没有EntityKey)? - 对于不触发刷新的按需唯一性检查,您还推荐什么其他解决方案?
【问题讨论】:
标签: hibernate grails grails-orm