GORM feature: Bypass Grails Domain Constraints
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’.
[groovy]
if(domainObject.validate([‘field1’, ‘field2’])){
domainObject.save(validate:false, flush:true)
}
[/groovy]
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.
[groovy]
Class User{
Long id
String name
String email
String password
static constraints = {
name(nullable: true)
}
}
[/groovy]
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.
[groovy]
User user = new User(name:userName, email:userEmail)
if(user.validate([’email’]) && user.save(validate:false, flush:true)){
return true
}
[/groovy]
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
Thanks dude
Appreciate you sharing, great blog.Thanks Again. Will read on…
thanks so much dude.. its really helpful