GORM feature: Bypass Grails Domain Constraints

15 / Oct / 2010 by Salil 3 comments

I didn’t know this earlier, but found a very good feature of GORM – ‘bypass’ constraints or ‘customize’ validation while saving a domain-object. I am not sure if there’s any name for this feature. But I am naming it as ‘bypass constraints’.

if(domainObject.validate(['field1', 'field2'])){
  domainObject.save(validate:false, flush:true)
}

Let’s discuss it with a use case. We create a user table with fields – id, name, email, password.
And email/password are mandatory fields.

Class User{
    Long id
    String name
    String email
    String password

    static constraints = {
        name(nullable: true)
    }
}

Now there’s a requirement in the application – An existing user can invite a friend.

With the help of ‘bypass constraints’ feature, it’s easier to handle this use-case without actually creating any separate domain to store invited users information.

Following code will create User entry with null password.

User user = new User(name:userName, email:userEmail)
if(user.validate(['email']) && user.save(validate:false, flush:true)){
return true
}


NOTE: To achieve this, you just need to set ‘password’ column as nullable true in your ‘user’ table.

Above example/use-case is just to explain ‘bypass constraints’ feature, nothing more than this. :-)

I hope it might help you somewhere.

Salil Kalia
salil [at] intelligrape.com

Tag -

FOUND THIS USEFUL? SHARE IT

comments (3)

Leave a comment -