Java Reference
In-Depth Information
Bean Validation
Bean validation, comes from Java Specification Request (JSR) 303, is a new addition
to the Java EE specification. Bean validation is implemented as a set of annotations
in the javax.validation package. 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 email addresses. Therefore
the wizard added the annotation with a regular expression used to match email
addresses, but since it couldn't be sure that this table is indeed meant to store email
addresses, it commented out this line of code. This property is indeed meant to store
email 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 our Customer entity shown above, 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 type java.util.
Collection , the Customer is the "one" side of the relationship, since a customer can
have many orders, many addresses (street, mail, etc), or many telephone numbers
(home, work, cell, etc.). 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.
 
Search WWH ::




Custom Search