Validating temporal fields

The java.util.Date and java.util.Calendar classes can be used to represent time in Java. If these classes are used for fields of an entity, the @Temporal annotation needs to be used. In addition, the @Future or @Past annotations are used to specify constraints on the relationship of the assigned date to the current time.

Getting ready

We will use the LicenseBean and LicenseBeanFacade classes from the ValidationApplication as discussed in the Validating persistent fields and properties recipe.

The @Temporal annotation designates a field as a time unit. JPA permits three basic mappings:

  • TemporalType.DATE
  • TemporalType.CALENDAR
  • TemporalType.TIMESTAMP

How to do it...

This annotation is used to annotate a Date or Calendar field as temporal data for a database column.

@Temporal(javax.persistence.TemporalType.DATE)
private Date dateOfBirth;

The @Temporal annotation can be used in conjunction with the @Future or @Past annotations to establish a constraint on the value of a field. The @Future requires the value of the field to be in the future. The use of the @Past requires the value of the field to be in the past which is expected for a field such as a birth date.

@Past
@Temporal(javax.persistence.TemporalType.DATE)
private Date dateOfBirth;

Below, we use the @Future annotation with the dateOfBirth field. While we would normally use the @Past annotation for this type of field, we will use it to illustrate a temporal constraint violation in the Using Validator class recipe.

@Future
@Temporal(javax.persistence.TemporalType.DATE)
private Date dateOfBirth;

How it works...

These annotations are used to control the assignment of temporal values to time-based fields. The javax.validation.Validator class is used in conjunction with these annotations to detect and handle violations. This technique is illustrated in the Using the Validator class recipe.

See also

The Using the Validator class recipe illustrates the use of this annotation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.151