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.
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:
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;
3.139.83.151