Wednesday, September 29, 2021

GRAILS 4 - how to disable deepvalidate in grails globally | Add ability to control cascading validation independently

How can we disable deepvalidate on global level in grails 4? as in our case on saving one domain object its trying to save all internal domain objects leading to different errors like unique constraint and all.

If GORM entity references some other entities, then during its constraints evaluation (validation) the constraints of the referenced entity could be evaluated also, if needed. There is a special parameter cascadeValidate in the entity mappings section, which manage the way of this cascaded validation happens.

You can do this in three ways
1. Define cascadeValidate as mapping per domain where needed:

class Author {
    Publisher publisher

    static mapping = {
        publisher(cascadeValidate: "none")
    }
}

class Publisher {
    String name

    static constraints = {
        name blank: false
    }
}
The following table presents all options, which can be used:

none: Will not do any cascade validation at all for the association.

default: The DEFAULT option. GORM performs cascade validation in some cases.

dirty: Only cascade validation if the referenced object is dirty via the DirtyCheckable trait. If the object doesn’t implement DirtyCheckable, this will fall back to default.

owned: Only cascade validation if the entity owns the referenced object.
2. It is possible to set the global option for the cascadeValidate:

Globally disable cascadeValidate in Grails 3 or 4 using:

grails {
    gorm {
        failOnError = true
        'default' {
            mapping = {
                cache true
                version false
                autoTimestamp false
                id generator:'assigned'
                '*'(cascadeValidate: 'none') // this one is the option to disable deep validate
            }
        }
    }
}
3. Alternatevely you can disable when call save() or merge() using:

new Account().save(validate: true, deepValidate: false)

Grails gorm reference link:

Reference https://gorm.grails.org/latest/hibernate/manual/#_cascade_constraints_validation

No comments:

Post a Comment