If validation mode is AUTO and a validation provider is found in classpath, or if validation mode is CALLBACK (a validation provider is required in classpath), then bean validation is enabled. For example,
META-INF/persistence.xml
<presistence ... > <persistence-unit name="pu_name"> <validation-mode>AUTO</validation-mode> </persistence-unit> </presistence>Bean validation annotations:
@MappedSuperclass public class Person { @Id @Column(length = 10) private String id; @Column(length = 20, nullable = false) private String name; @Temporal(TemporalType.DATE) @Past // bean validation protected Date birthday; } @Entity public class Employee extends Person { @ManyToOne @Null(groups = ValidationGroup1.class) // bean validation private Employee manager; @Column(length=30) private String jobTitle; @ElementCollection @Valid // bean validation: cascade @Size(max = 1, groups = ValidationGroup1.class) // bean validation private List<PhoneNumber> phoneNumbers; @Embedded @Valid // bean validation: cascade private Address address; } public class PhoneNumber { @NotNull // bean validation @Size(max = 3) // bean validation private String countryCode; @Size(min = 1, max = 3) // bean validation private String areaCode; @Size(min = 7, max = 7) // bean validation private String localNumber; } @Embeddable public class Address { @Column(length = 50) private String street; @Column(length = 30) private String city; @Column(length = 20) private String state; @Embedded @Valid // bean validation: cascade @NotNull // bean validation private ZipCode zipCode; } @Embeddable public class ZipCode { @Column(length = 5) @Pattern(regexp="\\d{5}") // bean validation private String majorCode; @Column(length = 4) @Pattern(regexp="\\d{4}") // bean validation private String minorCode; }
javax.persistence.validation.group.pre-persist javax.persistence.validation.group.pre-update javax.persistence.validation.group.pre-removeThey are defined in com.cmobilecom.jpa.Constants. Their values are a list of full qualified group class names separated by comma. For example,
import com.cmobilecom.jpa.Constants; ... Map<String, Object> properties = new HashMap<String, Object>(); properties.put(Constants.VALIDATION_GROUP_PRE_PERSIST, "com.cmobilecom.jpa.example.ValidationGroup1,com.cmobilecom.jpa.example.ValidationGroup2"); properties.put(Constants.VALIDATION_GROUP_PRE_UPDATE, "com.cmobilecom.jpa.example.ValidationGroup3"); properties.put(Constants.VALIDATION_GROUP_PRE_REMOVE, "com.cmobilecom.jpa.example.ValidationGroup4"); EntityManagerFactory emf = Persistence.createEntityManagerFactory("pu_name", properties); EntityManager em = emf.createEntityManager();ConstraintViolationException will be thrown if there are any validation constraints violated when the method persist(entity), merge(entity) or remove(entity) of EntityManager is called.