alternative to grails multicolumn unique constrain

2019-09-06 04:50发布

问题:

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.