Enterprise Java Development@TOPIC@

Chapter 54. Validation API/JPA Integration

54.1. Entity Class
54.2. Persistence Unit
54.3. Validation
54.4. Validation with JPA
54.5. Summary

JPA and Validation API annotations can be mixed together

@Entity

@Table(name="VALIDATION_PERSON")
public class Person {
    @Id @GeneratedValue
    private int id;
    
    @Column(name="FIRST_NAME", length=12, nullable=false)
    @ValidName(min=1, max=12, regexp="^[a-zA-Z\\ \\-]+$", message="invalid first name")
    private String firstName;
    
    @Column(name="LAST_NAME", length=20, nullable=false)
    @ValidName(min=1, max=20, regexp="^[a-zA-Z\\ \\-]+$", message="invalid last name")
    private String lastName;
    
    @Temporal(TemporalType.DATE)
    @NotNull(groups={Drivers.class, POCs.class})
    @Past(groups=Drivers.class)
    @MinAge.List({
        @MinAge(age=18, groups=POCs.class),
        @MinAge(age=16, groups=Drivers.class)
    })
    private Date birthDate;
    
    @Column(name="EMAIL", length=50)
    @NotNull(groups=POCs.class)
    @Size(min=7,max=50)
    @Pattern(regexp="^.+@.+\\..+$")
    private String email;
...

<?xml version="1.0" encoding="UTF-8"?>
<persistence ...

    <persistence-unit name="jpa-validation-example-test">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

        <validation-mode>AUTO</validation-mode>
        <properties>
            <property name="javax.persistence.validation.group.pre-persist" 
                      value="ejava.jpa.example.validation.Drivers"/>
            <property name="javax.persistence.validation.group.pre-update" 
                      value="ejava.jpa.example.validation.Drivers"/>
        </properties>
    </persistence-unit>            
</persistence>
Person p = new Person()

    .setFirstName("Bob")
    .setLastName("Smith")
    .setBirthDate(new Date());
try {
    em.persist(p);
} catch (ConstraintViolationException ex) {
    logger.info("caught expected exception:" + ex);
}
 -caught expected exception:javax.validation.ConstraintViolationException: 
     Validation failed for classes [ejava.jpa.example.validation.Person] 
     during persist time for groups [ejava.jpa.example.validation.Drivers, ]
List of constraint violations:[
    ConstraintViolationImpl{
        interpolatedMessage='too young', 
        propertyPath=birthDate, 
        rootBeanClass=class ejava.jpa.example.validation.Person, 
        messageTemplate='too young'}
    ConstraintViolationImpl{
        interpolatedMessage='0 is younger than minimum 16', 
        propertyPath=birthDate, 
        rootBeanClass=class ejava.jpa.example.validation.Person, 
        messageTemplate='0 is younger than minimum 16'}
]