liveBook · Manning

Java.util.Date

As explained in Java Persistence with Spring Data and Hibernate epub

java.util.Date is the legacy Java class representing a date and time as a millisecond-based value.

A java.util.Date property can hold a date and time in a Java entity, but its database column needs a temporal mapping. Use @Temporal to choose whether the column stores a date, a time, or a timestamp. Without @Temporal, the default is TemporalType.TIMESTAMP. section 6.1.6

The three TemporalType options select the stored part of the value:

Listing 6.6 Property of a temporal type that must be annotated with @Temporal
@CreationTimestamp
@Temporal(TemporalType.DATE)
private Date createdOn;
 
@UpdateTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date lastModified;

The entity-property example pairs @CreationTimestamp with DATE for createdOn and @UpdateTimestamp with TIMESTAMP for lastModified. The annotations make the intended database accuracy explicit. section 6.1.6

A property declared as java.util.Date need not load as that exact class. Hibernate returns java.sql.Date, java.sql.Time, or java.sql.Timestamp according to its temporal mapping. The JDBC subclasses preserve database accuracy: java.util.Date has millisecond accuracy, while java.sql.Timestamp can carry nanoseconds. This can make equals() comparisons between a java.util.Date and a loaded timestamp problematic. section 6.3.1

For new domain models, prefer the Java 8 java.time classes when they fit the required date or time value. JPA 2.2 supports them; java.util.Date remains relevant when mapping existing properties. section 6.3.1

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Explains @Temporal choices, loaded JDBC subclasses, precision, and an equality pitfall; stops short of a full persistence implementation.
Examples
Shows createdOn mapped as DATE and lastModified mapped as TIMESTAMP alongside creation and update timestamp annotations.
What it assumes
Assumes Java entity properties and annotations; introduces their DATE, TIME, and TIMESTAMP mapping choices.
What you can do after
Apply it via JPA @Temporal to select stored accuracy and diagnose equality surprises after Hibernate loads a JDBC subclass.
How it connects
Connects java.util.Date to @Temporal, TemporalType, JDBC date-time classes, SQL temporal types, and java.time.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.