What is the use of @Temporal annotation in JPA

Here you will know what is the use of @Temporal annotation in JPA. @Temporal is a JPA annotation and generally specified only for persistent fields or properties of type java.util.Date and java.util.Calendar. Generally you use @Temporal annotation on the date or calendar field in entity classes during table and Java class mapping where Hibernate is used as an ORM (Object Relational Mapping) framework.

You won’t be able to apply @Temporal annotation on Java 8 date time API. If you try to use @Temporal annotation on Java 8 date time API then you will get similar exception as shown below during run time of your application:

org.hibernate.AnnotationException: @Temporal should only be set on a java.util.Date or java.util.Calendar property

In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data, you might want to define the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (i.e., the actual date, only the time, or both). You can use the @Temporal annotation to the exact precision of the date, time or both.

Practically when you declare a Date field in the class and try to store it into database table, it will store the timestamp in the database. For example,

@Column(name="create_date")
private Date createDate;

So the value for the above field will be stored in the database, for example, 08-08-18 04:33:35.880000000 AM, but you may want to store only date value (not time) into the table’s column of the database. Here the use of @Temporal annotation in JPA comes to rescue on your Java Date or Calendar instance prior to Java 8.

Therefore declare the field in your entity class as shown below using the @Temporal annotation with TemporalType.DATE:

@Temporal(TemporalType.DATE)
@Column(name="create_date")
private Date createDate;

If you want to store only time then use below example using the @Temporal annotation with TemporalType.TIME:

@Temporal(TemporalType.TIME)
@Column(name="create_date")
private Date createDate;

If you want to store timestamp, i.e., date and time both then you can use below example using the @Temporal annotation with TemporalType.TIMESTAMP:

@Temporal(TemporalType.TIMESTAMP)
@Column(name="create_date")
private Date createDate;

Therefore from the above example in entity class we can conclude:

The @Temporal annotation in JPA will map Java’s (version less than 8) java.util.Date or java.util.Calendar to TIME (java.sql.Time), DATE(java.sql.Date) or TIMESTAMP (java.sql.Timestamp) in the database table’s column.

Thanks for reading.

Related posts

Leave a Comment