Search code examples
grailsgrails-ormunique-constraint

Grails - how setup unique constrain with thrown exception


I am trying to define unique constrain in DB. Let's take simple domain class

class Tag {

    String name

    static mapping = {
        sort name: "asc"
    }

    static constraints = {
        name(blank: false, nullable: false, unique: true)
    }
}

and then in controller

  def test() {

        def tag = new Tag(name: 'test');
        tag.save(flush:true);
        print tag.id

        tag = new Tag(name: 'test');
        tag.save(flush:true);
        print tag.id

        render "it works"
    }

the output is

1
null

My question is, how can I get exception after second save operation - it is important to know that second tag is not persisted so all further operations on it do not have sense.


Solution

  • You can achieve this behaviour using failOnError.

    But this way ValidationException is thrown when any validation error occurs, not only unique constraint.

      tag = new Tag(name: 'test');
      tag.save(flush:true, failOnError: true);
      print tag.id