Chaitanya Chaitanya - 3 months ago 22
Java Question

What is the use of the @Temporal annotation in Hibernate?

The Hibernate Documentation has the information below for the

@Temporal
annotation:


In plain Java APIs, the temporal precision of time is not defined.
When dealing with temporal data you might want to describe the
expected precision in database. Temporal data can have DATE, TIME, or
TIMESTAMP precision (ie the actual date, only the time, or both). Use
the @Temporal annotation to fine tune that.


What does
temporal precision of time is not defined
mean? What is
temporal
data and its precision? How does it fine tune?

Answer

This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.

The Temporal annotation may be used in conjunction with the Basic annotation, the Id annotation, or the ElementCollection annotation (when the element collection value is of such a temporal type.

@Temporal(DATE)
     protected java.util.Date endDate;

from some blog

In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data you might want to describe the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (ie the actual date, only the time, or both). Use the @Temporal annotation to fine tune that.

Information collected from various other sources

The temporal data is the data related to time. For example, in a content management system, the creation-date and last-updated date of an article are temporal data. In some cases, temporal data needs precision and you want to store precise date / time or both(TIMESTAMP) in database table.

The temporal precision is not specified in core Java APIs. @Temporal is a JPA annotation that convert back and forth between time-stamp and java util date. It also convert time-stamp into time. For example, in below snippet , ?@Temporal(TemporalType.DATE)? drops the time value and only preserves the date

@Temporal(TemporalType.DATE)
@Column(name=?CREATION_DATE?)
private java.util.Date date;

As per javadocs,

Annotation to declare an appropriate {@code TemporalType} on query method parameters. Note that this annotation can only be used on parameters of type {@link Date} with default TemporalType.DATE