Question

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.

Was it helpful?

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

OTHER TIPS

you could also see the exception raised during save() by adding below entry in your grails-app/conf/Config.groovy

grails.gorm.failOnError=true

The save method informs the persistence context that an instance should be saved or updated which can have following optional parameters

save(validate:true, flush:true, failOnError:true)

Parameters:

validate (optional) - Set to false if validation should be skipped

flush (optional) - When set to true flushes the persistence context, persisting the object immediately and updating the version column for optimistic locking

failOnError (optional) - When set to true the save method with throw a grails.validation.ValidationException if validation fails.

insert (optional) - When set to true will force Hibernate to do a SQL INSERT

deepValidate (optional) - Determines whether associations of the domain instance should also be validated, i.e. whether validation cascades. This is true by default - set to false to disable cascading validation.

try to use this way and see all the errors raised during save.

if (!tag.save()) {  
       tag.errors.each {  
        println it  
    }  
}

Hope this helps you

Regards
Motilal

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top