alternative to grails multicolumn unique constraint (optimistic inserts)

拈花ヽ惹草 提交于 2020-01-17 04:22:49

问题


I have a heavy used domain class Relationship which looks pretty similar to following one

class Relationship {
    Element source
    Element destination
    Type type

    // other properties omitted

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

I have a service creating new instances of this domain class which checks for existing instances and if found reuses them but I would like to implement sort of optimistic inserts with the unique constraint only in the database because

  1. GORM unique constraints are highly inefficient (for a simple task I got 13 000 hits just checking the constraints and one third of the time spent)
  2. finding the existing entity is expensive while running in batch (each query flushes the current session and costs about 40ms)

So the idea is to let the save method fail and than reuse the existing entity

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

but than when I try to find the entity I got hibernate exception

AssertionFailure: null id in Relationship entry (don't flush the Session after an exception occurs)
  1. Is there any way how to recover from the exception (relationshipInstance.discard() does not help as it does not have EntityKey)?
  2. What other solution would you recommend for on demand uniqueness checking without triggering flush?

回答1:


You can disable the validation when calling save, like this:

relationshipInstance.save(validate:false)

See documentation for save method for further info.



来源:https://stackoverflow.com/questions/29148220/alternative-to-grails-multicolumn-unique-constraint-optimistic-inserts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!