liveBook · Manning

Java.time

As explained in Java Persistence with Spring Data and Hibernate epub

The Java time API is the standard Java API for representing dates, times, date-times, and time-zone offsets.

For a persistent date or time property, prefer the Java 8 `java.time` API over `java.util.Date`, `java.util.Calendar`, and the `java.sql` date/time classes. JPA 2.2 officially supports these classes, which distinguish dates, times, date-times, and values with a UTC offset. section 6.3.1

Choose a type that matches the value being stored:

  • Use `LocalDate` for a SQL `DATE` and `LocalTime` or `OffsetTime` for a SQL `TIME`. section 6.3.1
  • Use `Instant`, `LocalDateTime`, `OffsetDateTime`, or `ZonedDateTime` for a SQL `TIMESTAMP`. `Duration` maps to `BIGINT`. section 6.3.1

The older `java.util.Date` mapping has a comparison trap: Hibernate may load it as a JDBC subclass such as `java.sql.Timestamp` to retain database precision. Its `equals()` behavior can then be asymmetric. If nanoseconds do not matter, compare Unix-time milliseconds instead. section 6.3.1

Table 6.3 Date and time types (view table figure)

Name

Java type

ANSI SQL type

date

java.util.Date, java.sql.Date

DATE

time

java.util.Date, java.sql.Time

TIME

timestamp

java.util.Date, java.sql.Timestamp

TIMESTAMP

calendar

java.util.Calendar

TIMESTAMP

calendar_date

java.util.Calendar

DATE

duration

java.time.Duration

BIGINT

instant

java.time.Instant

TIMESTAMP

localdatetime

java.time.LocalDateTime

TIMESTAMP

localdate

java.time.LocalDate

DATE

localtime

java.time.LocalTime

TIME

offsetdatetime

java.time.OffsetDateTime

TIMESTAMP

offsettime

java.time.OffsetTime

TIME

zoneddatetime

java.time.ZonedDateTime

TIMESTAMP

Compare the Java date/time classes with their ANSI SQL column types. section 6.3.1

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Compares supported classes and SQL mappings, then explains a legacy Date precision and equality pitfall; does not detail java.time internals.
Examples
Uses a type-mapping table and a java.util.Date versus java.sql.Timestamp equality case.
What you can do after
Apply it via JPA 2.2 and Hibernate to choose date/time property types and understand their SQL mappings.
How it connects
Connects java.time to JPA 2.2, Hibernate, JDBC types, SQL date/time columns, and temporal precision.

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.