Search code examples
jpabean-validation

JPA: what does bean validation mean for pre-remove?


JPA: what does bean validation mean for pre-remove?

public class Foo {

    @Past
    private Date date;
}

When removing entity Foo, if the date is valid (a past date), can the entity Foo be deleted or must not be deleted? When deleting an entity, why do we care whether the entity is valid or not?


Solution

  • The default behavior if Bean Validation is activated for JPA is to validate on the pre-persist and pre-update events.And the constraints that are validated are the ones in the default group (Default).

    To activate the validation for the pre-remove event, you have to set the configuration property javax.persistence.validation.group.pre-remove on your persistence.xml file to the value of the validation groups you want to apply.

    For example, you could create group (that's just an empty interface):

    public interface DeleteGroup {
    }
    

    And add a constraint to a field you want to test:

    public class Foo {
    
        @Past(groups = {DeleteGroup.class})
        private Date date;
    }
    

    And on the persistence.xml set the property:

    <property name="javax.persistence.validation.group.pre-remove" value="yourpackage.DeleteGroup" />
    

    Then, on a delete event, that constraint would be validated. It would not be validated on pre-insert or pre-update unless you assign it to the Default group too.

    This is an useful if you want to be sure that a record can't be deleted if it hasn't been processed (a field canBeDeleted is true for example), or meets some more complex criteria.