Bean Validation, NetBeans IDE, and the @Pattern Annotation
By Geertjan-Oracle on Feb 18, 2012
At Java Day St. Petersburg, during a session I did showing how the Java EE 6 specification maps to tools in NetBeans IDE 7.1 via an extended demo (no slides, just code), someone in the audience asked: "What is the @Pattern annotation in the Customer class generated by the NetBeans IDE JPA wizard and why is it commented out?"
Over the last week, I've been reading David Heffelfinger's excellent "Java EE 6 Development with NetBeans 7" and found the following section on page 221 (of a book of 370 pages or so), which answers the question above:
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.
As you can see from the above, what is great about David Heffelfinger's book is that it very succinctly (i.e., the above is literally everything you're going to find about bean validation in the whole book) explains the Java EE 6 specification, but in the context of the code generators that come with NetBeans IDE. That makes it a very pragmatic book indeed from which an incredible amount can be learned when you work through it with NetBeans IDE open in front of you.