2020-04-21

Hibernate JPA @Temporal Example

@Temporal

The @Temporal annotation is used to specify the TemporalType of the currently annotated java.util.Date or java.util.Calendar entity attribute.

Temporal This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.
The Temporal annotation may be used in conjunction with the Basic annotation, the Id annotation, or the ElementCollection annotation (when the element collection value is of such a temporal type.

     Example:

     @Temporal(DATE)
     protected java.util.Date endDate;

Mapping Date/Time Values

Hibernate allows various Java Date/Time classes to be mapped as persistent domain model entity properties. The SQL standard defines three Date/Time types:

DATE
Represents a calendar date by storing years, months and days. The JDBC equivalent is java.sql.Date

TIME
Represents the time of a day and it stores hours, minutes and seconds. The JDBC equivalent is java.sql.Time

TIMESTAMP
It stores both a DATE and a TIME plus nanoseconds. The JDBC equivalent is java.sql.Timestamp

java.util.Date mapped as DATE

@Entity(name = "DateEvent")
public static class DateEvent {

@Id
@GeneratedValue
private Long id;

@Column(name = "`timestamp`")
@Temporal(TemporalType.DATE)
private Date timestamp;

//Getters and setters are omitted for brevity

}

java.util.Date mapped as TIMESTAMP

@Column(name = "`timestamp`")
@Temporal(TemporalType.TIMESTAMP)
private Date timestamp;

No comments:

Post a Comment