Here we will know 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. This @Temporal annotation is generally we use on the date or calendar field in entity classes during table and Java class mapping where Hibernate is used as an ORM 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 to the following exception 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 above field will be stored like, for example, 08-08-18 04:33:35.880000000 AM, but you may want to store only date value into the database table column. 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 field declaration in your entity class we can see, the @Temporal annotation in JPA will map 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.
Thanks for reading.