Search code examples
javahibernatehibernate-annotations

Is TemporalType = Timestamp necessary if we want to store Date in Hibernate?


Is it necessary to give @Temporal, if we want to store Date in Hibernate?

@Column(name = "Date_Open")
@Temporal(TemporalType.TIMESTAMP)
public Date getDateOpen() {
  return this.dateOpen;
}

What will be default TemporalType if we do not use @Temporal annotation?

What will be default value if @Temporal is not given and what is benefit if it is given with TemporalType.Timestamp?


Solution

  • @Temporal not necessary to use with Date filed, by default hibernate save date with Timestamp, We can use the @Temporal annotation to specify the precision in which hibernate will save the date, time or timestamp. In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data, you might want to describe the expected precision in database. following Type used to indicate a specific mapping of java.util.Date or java.util.Calenda.

    TemporalType.DATE: maps the date as java.sql.Date.
    TemporalType.TIME: maps the date as java.sql.Time.
    TemporalType.TIMESTAMP: maps the date as java.sql.Timestamp.
    

    Here is nice explanation about @temporal

    Also about Absence of @Temporal annotation in date field:

    In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data you might want to describe the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (ie the actual date, only the time, or both). Use the @Temporal annotation to fine tune that.

    From 2.2.2.1. Declaring basic property mappings.

    This might indicate that the actual date representation in the database is not defined and to be sure it is better to specify it directly.