Home Hibernate @Temporal Annotation in JPA

@Temporal Annotation in JPA

- Advertisement -

1. Temporal annotation

The java.util or java.time properties need to explicitly mark the SQL type correlation with the @Temporal annotation prior to Java 8. @Temporal should only be set on a java.util.Date or java.util.Calendar property.

  • @Temporal  annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar.
  • @Temporal annotation solves the one of the major issue of converting the date and time values from Java object to compatible database type and retrieving back to the application.
  • The mapping between the Java 8 Date/Time classes and the SQL types is implicit, there is not need to specify the @Temporal annotation.
JPA Hibernate @Temporal
  • JPA supports  TemporalType.TIMESTAMPTemporalType.DATETemporalType.TIME.
  • These types are equivalent of  java.sql.Timestampjava.sql.Datejava.sql.Time.
jpa hibernate temporal annotation

Technologies Used in following example :

  • JPA 2.1
  • Hibernate 5.2.6
  • MySql 8.0
  • Maven 3
  • Spring Tool Suite (STS) 3.9.8
  • Java 1.8

2. @Temporal annotation mapping example

@Entity(name="USER")
public class User {
    
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    @Column(name = "ID")
    private Long id;
    
    @Column(name="USER_NAME")
    private String userName;
    
    @Column(name="PASSWORD")
    private String password;
    
    @Temporal(value=TemporalType.TIMESTAMP)
    @Column(name="CREATED_TIME")
    private Date creationTime;
    
    @Temporal(value=TemporalType.TIMESTAMP)
    @Column(name="UPDATED_TIME")
    private Date updatedTime;
    
    @Temporal(value=TemporalType.DATE)
    @Column(name="DOB")
    private Date dateofBirth;
    
    @Enumerated(value=EnumType.STRING)
    @Column(name="USER_TYPE")
    private UserType userType;
  • From the above snippet line numbers 16,20,24 describes the mapping of Temporal type to the Entity.
  • @Temporal annotation more useful to convert specific type either TimeStamp or Time or Date.

3.1 Test the mapping

public static void main( String[] args )
    {
        EntityManagerFactory emf = null;
        EntityManager entityManager = null;
        EntityTransaction transaction = null;
        
        try{
            emf = Persistence.createEntityManagerFactory("jbd-pu");
            entityManager = emf.createEntityManager();
            transaction = entityManager.getTransaction();
            transaction.begin();
            
            User user = new User();
            user.setUserName("mike");
            user.setPassword("password");
            // Setting Current Date
            user.setCreationTime(new Date());
            user.setDateofBirth(new Date());
            user.setUserType(UserType.EMPLOYEE);
    
            entityManager.persist(user);
            transaction.commit();
        }catch(Exception e){
            transaction.rollback();
        }finally{
            entityManager.close();
            emf.close();
        }
    }

Download Application – JPA-Temporal.zip (11 KB)

3.2. You might be interested in following articles

  1. Transient annotation in JPA and hibernate
  2. Hibernate Types

References

  1. Hibernate document

Satish Varma
Satish Varmahttps://javabydeveloper.com
Satish is post graduated in master of computer applications and experienced software engineer with focus on Spring, JPA, REST, TDD and web development. Also founder of javabydeveloper.com. Follow him on LinkedIn or Twitter or Facebook

2 COMMENTS

  1. […] ¿Qué Date resolver? Espero java.util.Date (correcta) y no java.sql.Date? La simple razón es que, al escribir entidades JPA está tratando de hacer un mapa de sus propiedades de entidad a la base de datos de las columnas (y tipos) y java.sql.Date ya está asignada tipo. Por lo que debe utilizar java.util.Date. Por favor, también tenga en cuenta que, por ejemplo, p:calendar (PrimeFaces) es que requieren java.util.Date y no java.util.Calendar (que me topé con él por mí mismo). Se refieren a: javabydeveloper.com/temporal […]

  2. […] Ce n' Date résoudre? J'espère java.util.Date (correct) et pas java.sql.Date? La simple raison est que, quand vous écrivez des entités, la JPA est d'essayer de mapper les propriétés d'entité de colonnes de base de données (et de genre) et java.sql.Date est déjà mappé type. Si vous devez utiliser java.util.Date. Veuillez également noter que, par exemple, p:calendar (PrimeFaces) exige de la java.util.Date et pas java.util.Calendar (je suis tombé sur ça par moi-même). Voir: javabydeveloper.com/temporal […]

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Stay in Touch

Categories