My preferred approach is to use JSR 303 (Bean Validation API) to make sure class properties are valid.
It is perfectly good to perform validation on setters, but this is not always desirable. There is the potential of mixing the needs of several contexts that are not related to each other. For example, some of your properties should never be set from the user interface and will instead be computed by the service before they are saved. In this case, it is undesirable to have this logic inside the setter, since you need to know the context in which the setter is called; you will need to apply different rules in your user interface layer and in your persistence level. JSR 303 allows you to separate these issues with validation groups so that your user interface validation group is different from your persistence verification group.
In JPA 2.0, when you comment on your class using constraints that are evaluated using JSR 303 validation, the persistence provider can automatically evaluate those constraints on PrePersist , PreUpdate and PreRemove (typically not executed; below) object life cycle events. To perform entity validation in your JPA provider, you must specify either the validation-mode element or the javax.persistence.validation.mode property in your persistence.xml file; values ββmust be either AUTO (default) or CALLBACK (not NONE ).
Having a Bean validation provider is sufficient to ensure that validation is performed on JPA object life cycle events, since the default value is AUTO . You get this by default on the Java EE 6 application server; Glassfish uses the RI JSR 303 implementation, which is the Hibernate Validator, and it works great with EclipseLink.
CALLBACK mode allows you to override the validation groups that will be applied when events in the life cycle are triggered. By default, the checked default Bean group ( Default ) will be checked to update and save events; The remove event does not require any validation. CALLBACK mode allows you to specify a different verification group for these events using the javax.persistence.validation.group.pre-persist , javax.persistence.validation.group.pre-update and javax.persistence.validation.group.pre-remove .
Keep in mind that JSR 303 validation can be used outside the Java EE container, although the link to the Bean API documentation I posted above is from the Java EE 6 API documentation.
source share