Java Reference
In-Depth Information
Adding Bean Validation
Bean Validation (JSR-303)
is a validation model available as part of the Java EE 6 plat-
form. The new 1.1 version (
JSR-349
) is a part of Java EE 7. The Bean Validation model is
supported by constraints in the form of annotations placed on a field, method, or class of a
JavaBeans component, such as a managed bean.
In our example, the
SeatType
entity will be created using an input form; therefore, we
will need to validate the data that has been entered by the user.
In our example, we will place a
@javax.validation.constraints.NotNull
constraint in every field that is part of the
SeatType
entry form, and a more complex
constraint in the
description
field, which will set the maximum size for the seat de-
scription to
25
(the
@javax.validation.constraints.Size
constraint) and al-
low just letters and spaces in it (the
@javax.validation.constraints.Pattern
constraint):
@Entity
@Table(name="seat_type)
public class SeatType implements Serializable {
private static final long serialVersionUID = 3643635L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
@NotNull
@Size(min = 1, max = 25, message = "You need to enter a
Seat Description (max 25 char)")
@Pattern(regexp = "[A-Za-z ]*", message = "Description
must contain only letters and spaces")
private String description;
@NotNull
private Integer price;
@NotNull