Java Reference
In-Depth Information
Bean Validation
Bean Validation
, which comes from Java Specification Request (JSR 303), was
introduced in Java EE 6. The Bean Validation specification provides a set of
annotations we can use to validate our data. The NetBeans JPA generation wizard
takes full advantage of Bean Validation, adding Bean Validation annotations to
any appropriate fields, based on the column definitions of the tables we are using
to generate our entities.
In our
Customer
entity, we see some Bean Validation annotations. The
customerId
field is decorated with the
@NotNull
annotation, which—as
its name implies—prevents the field from accepting a null value.
Several fields in the
Customer
entity are decorated with the
@Size
annotation. This
annotation specifies the maximum number of characters a bean's property may
accept. Again, the NetBeans wizard obtains this information from the tables used
to generate our entity.
Another Bean Validation annotation we can use is the
@Pattern
annotation. This
annotation is meant to make sure that the value of the decorated field matches a
given regular expression.
Notice that right above the
email
property of the
Customer
annotation, the wizard
added the
@Pattern
annotation and commented it out. The reason for this is that
the wizard noticed that the name of the table column was
EMAIL
and suspected
(but couldn't verify) that this table is meant to store e-mail addresses. Therefore,
the wizard added the annotation with a regular expression used to match e-mail
addresses. However, since it couldn't be sure that this table is indeed meant
to store e-mail addresses, it commented out this line of code. This property is
indeed meant to store e-mail addresses, therefore we should uncomment this
automatically-generated line.
Entity relationships
There are several annotations we can use in JPA entities to define relationships
between them. In the
Customer
entity we discussed, we can see that the wizard
detected several one-to-many relationships in the
CUSTOMER
table and automatically
added the
@OneToMany
annotation to define these relationships in our entity. Notice
that each field annotated with the
@OneToMany
annotation is of the type
java.util.
Collection
. The
Customer
entity is one side of the relationship, since a customer
can have many orders, many addresses (street, e-mail, and so on), or many telephone
numbers (home, work, cell, and so on). Notice that the wizard uses generics to
specify the type of objects we can add to each collection. Objects in these collections
are the JPA entities mapping to the corresponding tables in our database schema.