What Is The Use Of @Temporal Annotation In JPA

@Temporal Annotation

In this tutorial I am going to tell you what is the use of @Temporal annotation in JPA (Java Persistence API). @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 can use @Temporal annotation on the date or calendar field in entity classes while you are mapping database table and Java classes where Hibernate is used as an ORM (Object Relational Mapping) framework.

@Temporal in Java 8 Date API

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

@Temporal in Java Date API

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,

private Date createDate;

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

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

private Date createDate;

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

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:

private Date createDate;

Therefore from the above example in entity class it can be concluded:

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.

That’s all about @Temporal annotation usage in Java application using JPA.

Leave a Reply

Your email address will not be published. Required fields are marked *