Hibernate : How to use @Temporal annotation
Points To Remember
@Temporal annotation must be used with the persistent fields or properties of type- java.util.Date
- java.util.Calendar
How to use @Temporal annotation
@Temporal Annotation is defined as following@Target({ METHOD, FIELD })
@Retention(RUNTIME)
public @interface Temporal {
/**
* The type used in mapping <code>java.util.Date</code> or <code>java.util.Calendar</code>.
*/
TemporalType value();
}
So the TemporalType is an Enum and looks like following
public enum TemporalType {
DATE,
TIME,
TIMESTAMP
}
So @Temporal annotation can take three values DATE, TIME and TIMESTAMP. And it will create the following database ddl type.
| TemporalType | Database DDL Type |
|---|---|
| DATE | date |
| TIMESTAMP | datetime |
| TIME | time |
If we the following class as Hibernate Entity
package com.ekiras.domian;
import javax.persistence.*;
import java.util.Date;
@Entity
public class User {
@Id
@SequenceGenerator(name = "test")
@GeneratedValue(strategy = GenerationType.AUTO, generator = "test")
private Long id;
@Temporal(value = TemporalType.DATE)
private Date dateCreated1;
@Temporal(value = TemporalType.TIMESTAMP)
private Date dateCreated2;
@Temporal(value = TemporalType.TIME)
private Date dateCreated3;
// GETTERS and SETTERS
}
It will create the output as shown in the image below.
If we try to add @Temporal annotation to any other field other than of type Date and Calender we will get the following exception
Caused by: org.hibernate.AnnotationException: @Temporal should only be set on a java.util.Date or java.util.Calendar property: com.ekiras.domian.User.name at org.hibernate.cfg.annotations.SimpleValueBinder.setType(SimpleValueBinder.java:182) at org.hibernate.cfg.annotations.PropertyBinder.makePropertyAndValue(Propertyjava:195) at org.hibernate.cfg.annotations.PropertyBinder.makePropertyValueAndBind(PropertyBinder.java:216) at org.hibernate.cfg.AnnotationBinder.processElementAnnotations(AnnotationBinder.java:2241) at org.hibernate.cfg.AnnotationBinder.processIdPropertiesIfNotAlready(AnnotationBinder.java:963) at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:796) at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3845) at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3799) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1412) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857) ... 23 more

No comments: