Add date-time module: Instant vs LocalDateTime vs OffsetDateTime vs ZonedDateTime round-tripped across JVM time zones on H2 and PostgreSQL

Hibernate 7.4.14.Final (plus an 8.0.0.Beta4 preview run), H2 2.5.252, PostgreSQL 17.11 in Docker.
Same-JVM and cross-zone round trips, @TimeZoneStorage modes, DST gap/overlap, precision
(precision vs secondPrecision), hibernate.jdbc.time_zone, java_time_use_direct_jdbc default flip.
Supersedes the date/time experiments of docs/13 (7.4.5); chapter 13 is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b7rnC7jppGGdHGESvy
This commit is contained in:
2026-10-29 00:56:54 +00:00
committed by Claude
co-authored by Claude Sonnet 5.5
parent c9faf35e61
commit ef2d2aa8ea
149 changed files with 2374 additions and 0 deletions
@@ -0,0 +1,75 @@
package com.ankurm.datetime;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.nio.file.Path;
import java.util.Map;
/**
* Builds a plain Hibernate SessionFactory against H2 or PostgreSQL. Everything the tests vary comes
* in through system properties so one compiled test class can run in any JVM time zone:
* dt.db = h2 | postgres | hsqldb, dt.pg.url, dt.phase = both | write | read, dt.directJdbc = default | true | false.
*/
public final class Db {
private Db() {
}
public static String kind() {
return System.getProperty("dt.db", "h2");
}
public static String phase() {
return System.getProperty("dt.phase", "both");
}
/**
* The effective value of hibernate.type.java_time_use_direct_jdbc: the explicit dt.directJdbc if
* given, otherwise the default of the Hibernate line under test (false on 7.x, true on 8.0 beta).
*/
public static boolean directJdbc() {
String v = System.getProperty("dt.directJdbc", "default");
return v.equals("default") ? System.getProperty("h.label", "h7").equals("h8") : Boolean.parseBoolean(v);
}
public static boolean available() {
return !kind().equals("postgres") || !System.getProperty("dt.pg.url", "none").equals("none");
}
public static String jdbcUrl() {
if (kind().equals("postgres")) {
return System.getProperty("dt.pg.url");
}
if (kind().equals("hsqldb")) {
return "jdbc:hsqldb:mem:dt"; // same-JVM only; used for the precision comparison
}
// File database so a second JVM (with a different time zone) can read what the first wrote.
Path file = Path.of("target", "h2-data", "dt").toAbsolutePath();
return "jdbc:h2:file:" + file;
}
/** @param create true drops and recreates the tables, false only validates that they exist. */
public static SessionFactory open(boolean create, Map<String, String> extra, Class<?>... entities) {
Configuration cfg = new Configuration();
for (Class<?> e : entities) {
cfg.addAnnotatedClass(e);
}
cfg.setProperty("hibernate.connection.url", jdbcUrl());
if (kind().equals("postgres")) {
cfg.setProperty("hibernate.connection.username", "postgres");
cfg.setProperty("hibernate.connection.password", "postgres");
}
else {
cfg.setProperty("hibernate.connection.username", "sa");
cfg.setProperty("hibernate.connection.password", "");
}
cfg.setProperty("hibernate.hbm2ddl.auto", create ? "create" : "validate");
String direct = System.getProperty("dt.directJdbc", "default");
if (!direct.equals("default")) {
cfg.setProperty("hibernate.type.java_time_use_direct_jdbc", direct);
}
extra.forEach(cfg::setProperty);
return cfg.buildSessionFactory();
}
}
@@ -0,0 +1,78 @@
package com.ankurm.datetime;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.hibernate.annotations.TimeZoneColumn;
import org.hibernate.annotations.TimeZoneStorage;
import org.hibernate.annotations.TimeZoneStorageType;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
/**
* One row, one column per way of storing "a moment" with java.time. The test writes the same
* moment into every column and reads it back in a new session (and, in the cross-zone runs, in a
* different JVM with a different default time zone).
*/
@Entity
@Table(name = "event")
public class Event {
@Id
private Long id;
/** A point on the UTC time line. */
@Column(name = "instant_col")
private Instant instant;
/** A calendar date and wall-clock time with no zone and no offset. */
@Column(name = "ldt_col")
private LocalDateTime localDateTime;
/** Hibernate's default storage for OffsetDateTime (dialect-derived, see 05-ddl). */
@Column(name = "odt_default_col")
private OffsetDateTime offsetDefault;
@TimeZoneStorage(TimeZoneStorageType.NATIVE)
@Column(name = "odt_native_col")
private OffsetDateTime offsetNative;
@TimeZoneStorage(TimeZoneStorageType.NORMALIZE)
@Column(name = "odt_normalize_col")
private OffsetDateTime offsetNormalize;
@TimeZoneStorage(TimeZoneStorageType.NORMALIZE_UTC)
@Column(name = "odt_normalize_utc_col")
private OffsetDateTime offsetNormalizeUtc;
@TimeZoneStorage(TimeZoneStorageType.COLUMN)
@TimeZoneColumn(name = "odt_column_col_offset")
@Column(name = "odt_column_col")
private OffsetDateTime offsetColumn;
protected Event() {
}
public Event(Long id) {
this.id = id;
}
public Long getId() { return id; }
public Instant getInstant() { return instant; }
public void setInstant(Instant v) { this.instant = v; }
public LocalDateTime getLocalDateTime() { return localDateTime; }
public void setLocalDateTime(LocalDateTime v) { this.localDateTime = v; }
public OffsetDateTime getOffsetDefault() { return offsetDefault; }
public void setOffsetDefault(OffsetDateTime v) { this.offsetDefault = v; }
public OffsetDateTime getOffsetNative() { return offsetNative; }
public void setOffsetNative(OffsetDateTime v) { this.offsetNative = v; }
public OffsetDateTime getOffsetNormalize() { return offsetNormalize; }
public void setOffsetNormalize(OffsetDateTime v) { this.offsetNormalize = v; }
public OffsetDateTime getOffsetNormalizeUtc() { return offsetNormalizeUtc; }
public void setOffsetNormalizeUtc(OffsetDateTime v) { this.offsetNormalizeUtc = v; }
public OffsetDateTime getOffsetColumn() { return offsetColumn; }
public void setOffsetColumn(OffsetDateTime v) { this.offsetColumn = v; }
}
@@ -0,0 +1,49 @@
package com.ankurm.datetime;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.Duration;
import java.time.Year;
import java.time.YearMonth;
import java.util.Date;
/** Types people ask about: a java.util.Date with no @Temporal, and the java.time types with no SQL twin. */
@Entity
@Table(name = "legacy")
public class Legacy {
@Id
private Long id;
/** No @Temporal annotation at all. */
@Column(name = "util_date_col")
private Date utilDate;
@Column(name = "year_col")
private Year year;
@Column(name = "year_month_col")
private YearMonth yearMonth;
@Column(name = "duration_col")
private Duration duration;
protected Legacy() {
}
public Legacy(Long id, Date utilDate, Year year, YearMonth yearMonth, Duration duration) {
this.id = id;
this.utilDate = utilDate;
this.year = year;
this.yearMonth = yearMonth;
this.duration = duration;
}
public Date getUtilDate() { return utilDate; }
public Year getYear() { return year; }
public YearMonth getYearMonth() { return yearMonth; }
public Duration getDuration() { return duration; }
}
@@ -0,0 +1,54 @@
package com.ankurm.datetime;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.Instant;
import java.time.LocalDateTime;
/** The same LocalDateTime/Instant under different @Column precision attributes. */
@Entity
@Table(name = "precision_event")
public class PrecisionEvent {
@Id
private Long id;
/** No precision attribute at all: the dialect's default. */
@Column(name = "ldt_default")
private LocalDateTime defaultPrecision;
/** The attribute the old advice reaches for. */
@Column(name = "ldt_precision9", precision = 9)
private LocalDateTime precision9;
/** The attribute Jakarta Persistence 3.2 added for exactly this. */
@Column(name = "ldt_second_precision9", secondPrecision = 9)
private LocalDateTime secondPrecision9;
@Column(name = "ldt_second_precision3", secondPrecision = 3)
private LocalDateTime secondPrecision3;
@Column(name = "instant_second_precision9", secondPrecision = 9)
private Instant instantSecondPrecision9;
protected PrecisionEvent() {
}
public PrecisionEvent(Long id, LocalDateTime value) {
this.id = id;
this.defaultPrecision = value;
this.precision9 = value;
this.secondPrecision9 = value;
this.secondPrecision3 = value;
this.instantSecondPrecision9 = value.toInstant(java.time.ZoneOffset.UTC);
}
public LocalDateTime getDefaultPrecision() { return defaultPrecision; }
public LocalDateTime getPrecision9() { return precision9; }
public LocalDateTime getSecondPrecision9() { return secondPrecision9; }
public LocalDateTime getSecondPrecision3() { return secondPrecision3; }
public Instant getInstantSecondPrecision9() { return instantSecondPrecision9; }
}
@@ -0,0 +1,48 @@
package com.ankurm.datetime;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
/** A narrow entity for the edge cases: DST gaps and overlaps, and sub-microsecond precision. */
@Entity
@Table(name = "probe")
public class Probe {
@Id
private Long id;
@Column(name = "label")
private String label;
@Column(name = "ldt_col")
private LocalDateTime localDateTime;
@Column(name = "instant_col")
private Instant instant;
@Column(name = "odt_col")
private OffsetDateTime offsetDateTime;
protected Probe() {
}
public Probe(Long id, String label) {
this.id = id;
this.label = label;
}
public Long getId() { return id; }
public String getLabel() { return label; }
public LocalDateTime getLocalDateTime() { return localDateTime; }
public void setLocalDateTime(LocalDateTime v) { this.localDateTime = v; }
public Instant getInstant() { return instant; }
public void setInstant(Instant v) { this.instant = v; }
public OffsetDateTime getOffsetDateTime() { return offsetDateTime; }
public void setOffsetDateTime(OffsetDateTime v) { this.offsetDateTime = v; }
}
@@ -0,0 +1,42 @@
package com.ankurm.datetime;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import org.hibernate.annotations.TimeZoneColumn;
import org.hibernate.annotations.TimeZoneStorage;
import org.hibernate.annotations.TimeZoneStorageType;
import java.time.ZonedDateTime;
/** ZonedDateTime on its own entity, because on some driver settings it cannot be bound or read at all. */
@Entity
@Table(name = "zoned_event")
public class ZonedEvent {
@Id
private Long id;
/** Hibernate's default storage for ZonedDateTime. */
@Column(name = "zdt_default_col")
private ZonedDateTime zonedDefault;
@TimeZoneStorage(TimeZoneStorageType.COLUMN)
@TimeZoneColumn(name = "zdt_column_col_offset")
@Column(name = "zdt_column_col")
private ZonedDateTime zonedColumn;
protected ZonedEvent() {
}
public ZonedEvent(Long id) {
this.id = id;
}
public Long getId() { return id; }
public ZonedDateTime getZonedDefault() { return zonedDefault; }
public void setZonedDefault(ZonedDateTime v) { this.zonedDefault = v; }
public ZonedDateTime getZonedColumn() { return zonedColumn; }
public void setZonedColumn(ZonedDateTime v) { this.zonedColumn = v; }
}
@@ -0,0 +1,139 @@
package com.ankurm.datetime;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.*;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.*;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Edge cases, always same-JVM: a LocalDateTime that does not exist in New York (the spring-forward
* gap), one that happens twice (the fall-back overlap), and nanosecond precision.
*/
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class EdgeCasesTest {
static final LocalDateTime GAP = LocalDateTime.of(2026, 3, 8, 2, 30);
static final LocalDateTime OVERLAP = LocalDateTime.of(2026, 11, 1, 1, 30);
static final LocalDateTime PLAIN = LocalDateTime.of(2026, 6, 15, 14, 0);
@BeforeAll
static void needDatabase() {
Assumptions.assumeTrue(Db.available(), "dt.db=postgres but dt.pg.url is not set");
Assumptions.assumeTrue(!Db.phase().equals("read") && !Db.phase().equals("write"),
"edge cases run only in same-JVM mode");
}
@Test
@Order(1)
void localDateTimeAroundDst() {
try (SessionFactory sf = Db.open(true, Map.of(), Probe.class)) {
List<Probe> in = List.of(probe(1, "plain wall clock", PLAIN), probe(2, "gap 02:30 on 2026-03-08", GAP),
probe(3, "overlap 01:30 on 2026-11-01", OVERLAP));
sf.inTransaction(s -> in.forEach(s::persist));
try (Session s = sf.openSession()) {
String product = s.doReturningWork(Transcript::product);
Transcript t = new Transcript("02-dst", "local-date-time", product);
t.line("# New York springs forward 2026-03-08 02:00 -> 03:00 and falls back 2026-11-01 02:00 -> 01:00");
for (Probe p : in) {
Probe out = s.find(Probe.class, p.getId());
String raw = raw(s, "ldt_col", p.getId());
t.line(String.format("%-28s in %-17s | out %-17s | equals %-5s | raw %s", p.getLabel(),
p.getLocalDateTime(), out.getLocalDateTime(),
p.getLocalDateTime().equals(out.getLocalDateTime()), raw));
}
t.write();
// A plain wall-clock time must always survive.
assertThat(s.find(Probe.class, 1L).getLocalDateTime()).isEqualTo(PLAIN);
assertThat(s.find(Probe.class, 3L).getLocalDateTime()).isEqualTo(OVERLAP);
// A time inside New York's spring-forward gap exists nowhere on the NY clock. With the
// legacy java.sql conversion (7.x default) the JVM moves it to 03:30; direct JDBC keeps it.
boolean newYork = ZoneId.systemDefault().getId().equals("America/New_York");
LocalDateTime expectedGap = newYork && !Db.directJdbc() ? GAP.plusHours(1) : GAP;
assertThat(s.find(Probe.class, 2L).getLocalDateTime()).isEqualTo(expectedGap);
}
}
}
@Test
@Order(2)
void precision() {
try (SessionFactory sf = Db.open(true, Map.of(), Probe.class)) {
int[] nanos = { 123_456_789, 123_456_500, 999_999_999, 123_456_499 };
sf.inTransaction(s -> {
long id = 10;
for (int n : nanos) {
Probe p = probe(id++, "nanos " + n, null);
p.setLocalDateTime(LocalDateTime.of(2026, 6, 15, 14, 0, 0, n));
p.setInstant(Instant.parse("2026-06-15T08:30:00Z").plusNanos(n));
p.setOffsetDateTime(OffsetDateTime.of(2026, 6, 15, 14, 0, 0, n, ZoneOffset.ofHoursMinutes(5, 30)));
s.persist(p);
}
});
try (Session s = sf.openSession()) {
String product = s.doReturningWork(Transcript::product);
Transcript t = new Transcript("03-precision", "", product);
t.line("# written: 14:00:00.<nanos> local / 08:30:00.<nanos>Z / 14:00:00.<nanos>+05:30 ; read back below (columns are timestamp(6))");
long id = 10;
for (int n : nanos) {
Probe out = s.find(Probe.class, id++);
t.line(String.format("nanos .%09d -> LocalDateTime %s | Instant %s | OffsetDateTime %s",
n, out.getLocalDateTime(), out.getInstant(), out.getOffsetDateTime()));
}
t.write();
// Whatever the engine does with the last three digits, microseconds are never invented.
Probe first = s.find(Probe.class, 10L);
assertThat(first.getInstant().getNano() % 1000).isZero();
}
}
}
@Test
@Order(3)
void generatedColumnTypes() {
try (SessionFactory sf = Db.open(true, Map.of(), Event.class, ZonedEvent.class);
Session s = sf.openSession()) {
String product = s.doReturningWork(Transcript::product);
Transcript t = new Transcript("05-ddl", "", product);
t.line("# column types Hibernate generated (information_schema.columns)");
List<String> rows = s.doReturningWork(c -> {
try (Statement st = c.createStatement();
ResultSet rs = st.executeQuery("select table_name, column_name, data_type, datetime_precision "
+ "from information_schema.columns where lower(table_name) in ('event', 'zoned_event') "
+ "and lower(table_schema) = 'public' order by table_name, ordinal_position")) {
List<String> out = new java.util.ArrayList<>();
while (rs.next()) {
out.add(String.format("%-12s %-24s %-28s precision %s", rs.getString(1).toLowerCase(), rs.getString(2).toLowerCase(),
rs.getString(3).toLowerCase(), rs.getString(4)));
}
return out;
}
});
rows.forEach(t::line);
t.write();
assertThat(rows).hasSize(13);
}
}
private static Probe probe(long id, String label, LocalDateTime ldt) {
Probe p = new Probe(id, label);
p.setLocalDateTime(ldt);
return p;
}
private static String raw(Session s, String column, long id) {
return s.doReturningWork(c -> {
try (Statement st = c.createStatement();
ResultSet rs = st.executeQuery("select cast(" + column + " as varchar) from probe where id = " + id)) {
rs.next();
return rs.getString(1);
}
});
}
}
@@ -0,0 +1,96 @@
package com.ankurm.datetime;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.*;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.*;
import java.util.Map;
import java.util.TimeZone;
import static org.assertj.core.api.Assertions.assertThat;
/**
* hibernate.jdbc.time_zone and hibernate.type.preferred_instant_jdbc_type, the two settings the old
* advice reaches for. Same-JVM only.
*/
class JdbcTimeZoneTest {
static final LocalDateTime WALL = LocalDateTime.of(2026, 7, 4, 9, 0);
static final Instant MOMENT = Instant.parse("2026-07-04T03:30:00Z");
@BeforeAll
static void needDatabase() {
Assumptions.assumeTrue(Db.available(), "dt.db=postgres but dt.pg.url is not set");
Assumptions.assumeTrue(!Db.phase().equals("read") && !Db.phase().equals("write"));
}
/** Always the zone the JVM is not in, so the setting visibly disagrees with the JVM. */
static String otherZone() {
return TimeZone.getDefault().getID().equals("America/New_York") ? "Asia/Kolkata" : "America/New_York";
}
@Test
void jdbcTimeZoneShiftsWhatIsBound() {
String zone = otherZone();
try (SessionFactory sf = Db.open(true, Map.of("hibernate.jdbc.time_zone", zone), Probe.class)) {
Probe p = new Probe(1L, "jdbc.time_zone=" + zone);
p.setLocalDateTime(WALL);
p.setInstant(MOMENT);
p.setOffsetDateTime(OffsetDateTime.of(WALL, ZoneOffset.ofHoursMinutes(5, 30)));
sf.inTransaction(s -> s.persist(p));
try (Session s = sf.openSession()) {
Probe out = s.find(Probe.class, 1L);
String[] raw = s.doReturningWork(c -> {
try (Statement st = c.createStatement();
ResultSet rs = st.executeQuery("select cast(ldt_col as varchar), cast(instant_col as varchar), "
+ "cast(odt_col as varchar) from probe where id = 1")) {
rs.next();
return new String[] { rs.getString(1), rs.getString(2), rs.getString(3) };
}
});
Transcript t = new Transcript("06-jdbc-time-zone", "", s.doReturningWork(Transcript::product));
t.line("# hibernate.jdbc.time_zone=" + zone + " while the JVM default zone is " + TimeZone.getDefault().getID());
t.line("LocalDateTime in " + WALL + " | out " + out.getLocalDateTime() + " | raw " + raw[0]);
t.line("Instant in " + MOMENT + " | out " + out.getInstant() + " | raw " + raw[1]);
t.line("OffsetDateTime in " + p.getOffsetDateTime() + " | out " + out.getOffsetDateTime() + " | raw " + raw[2]);
t.write();
// Through Hibernate the round trip is transparent whatever the setting says.
assertThat(out.getLocalDateTime()).isEqualTo(WALL);
assertThat(out.getInstant()).isEqualTo(MOMENT);
assertThat(out.getOffsetDateTime().toInstant()).isEqualTo(p.getOffsetDateTime().toInstant());
}
}
}
@Test
void preferredInstantJdbcType() {
for (String type : new String[] { "TIMESTAMP", "TIMESTAMP_UTC" }) {
try (SessionFactory sf = Db.open(true, Map.of("hibernate.type.preferred_instant_jdbc_type", type), Probe.class)) {
Probe p = new Probe(1L, "preferred_instant_jdbc_type=" + type);
p.setInstant(MOMENT);
sf.inTransaction(s -> s.persist(p));
try (Session s = sf.openSession()) {
Probe out = s.find(Probe.class, 1L);
String[] r = s.doReturningWork(c -> {
try (Statement st = c.createStatement();
ResultSet rs = st.executeQuery("select cast(instant_col as varchar), (select data_type from "
+ "information_schema.columns where lower(table_name) = 'probe' and "
+ "lower(column_name) = 'instant_col' and lower(table_schema) = 'public') from probe where id = 1")) {
rs.next();
return new String[] { rs.getString(1), rs.getString(2).toLowerCase() };
}
});
Transcript t = new Transcript("07-preferred-instant-jdbc-type", type.toLowerCase(),
s.doReturningWork(Transcript::product));
t.line("# hibernate.type.preferred_instant_jdbc_type=" + type);
t.line("column type " + r[1] + " | Instant in " + MOMENT + " | out " + out.getInstant() + " | raw " + r[0]);
t.write();
assertThat(out.getInstant()).isEqualTo(MOMENT);
}
}
}
}
}
@@ -0,0 +1,130 @@
package com.ankurm.datetime;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.*;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.*;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Writes one moment (2026-06-15T08:30:00Z) into every temporal column of {@link Event}, then reads
* it back in a brand-new session. With dt.phase=both both steps run in this JVM; with
* dt.phase=write / dt.phase=read they run in two JVMs with different -Duser.timezone values.
*/
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class RoundTripTest {
static final Instant MOMENT = Instant.parse("2026-06-15T08:30:00Z");
static final LocalDateTime WALL = LocalDateTime.of(2026, 6, 15, 14, 0);
static final OffsetDateTime KOLKATA = OffsetDateTime.of(WALL, ZoneOffset.ofHoursMinutes(5, 30));
@BeforeAll
static void needDatabase() {
Assumptions.assumeTrue(Db.available(), "dt.db=postgres but dt.pg.url is not set");
}
@Test
@Order(1)
void write() {
Assumptions.assumeTrue(!Db.phase().equals("read"));
try (SessionFactory sf = Db.open(true, Map.of(), Event.class)) {
Event e = new Event(1L);
e.setInstant(MOMENT);
e.setLocalDateTime(WALL);
e.setOffsetDefault(KOLKATA);
e.setOffsetNative(KOLKATA);
e.setOffsetNormalize(KOLKATA);
e.setOffsetNormalizeUtc(KOLKATA);
e.setOffsetColumn(KOLKATA);
sf.inTransaction(s -> s.persist(e));
}
}
@Test
@Order(2)
void read() {
Assumptions.assumeTrue(!Db.phase().equals("write"));
try (SessionFactory sf = Db.open(false, Map.of(), Event.class);
Session s = sf.openSession()) {
String product = s.doReturningWork(Transcript::product);
Event e = s.find(Event.class, 1L);
String[] raw = s.doReturningWork(c -> {
try (Statement st = c.createStatement();
ResultSet rs = st.executeQuery("select cast(instant_col as varchar), cast(ldt_col as varchar), "
+ "cast(odt_default_col as varchar), cast(odt_native_col as varchar), "
+ "cast(odt_normalize_col as varchar), cast(odt_normalize_utc_col as varchar), "
+ "cast(odt_column_col as varchar) from event where id = 1")) {
rs.next();
String[] r = new String[7];
for (int i = 0; i < 7; i++) {
r[i] = rs.getString(i + 1);
}
return r;
}
});
String writer = System.getProperty("dt.writerZone", "?").replace('/', '_');
String variant = Db.phase().equals("read") ? "written-in-" + writer : "same-jvm";
Transcript t = new Transcript("01-roundtrip", variant, product);
if (Db.phase().equals("read")) {
t.line("# written by another JVM whose default zone was " + System.getProperty("dt.writerZone")
+ "; this JVM only reads (see scripts/run-all.sh)");
}
t.line("# written: Instant " + MOMENT + ", LocalDateTime " + WALL + ", OffsetDateTime " + KOLKATA
+ " (all the same moment; the LocalDateTime is the Kolkata wall clock)");
t.line(row("Instant", MOMENT, e.getInstant(), raw[0]));
t.line(row("LocalDateTime", WALL, e.getLocalDateTime(), raw[1]));
t.line(row("OffsetDateTime default", KOLKATA, e.getOffsetDefault(), raw[2]));
t.line(row("OffsetDateTime NATIVE", KOLKATA, e.getOffsetNative(), raw[3]));
t.line(row("OffsetDateTime NORMALIZE", KOLKATA, e.getOffsetNormalize(), raw[4]));
t.line(row("OffsetDateTime NORMALIZE_UTC", KOLKATA, e.getOffsetNormalizeUtc(), raw[5]));
t.line(row("OffsetDateTime COLUMN", KOLKATA, e.getOffsetColumn(), raw[6]));
t.write();
// What must hold on every database and in every JVM zone:
assertThat(e.getInstant()).isEqualTo(MOMENT);
assertThat(e.getLocalDateTime()).isEqualTo(WALL);
for (OffsetDateTime o : new OffsetDateTime[] { e.getOffsetDefault(), e.getOffsetNative(),
e.getOffsetNormalizeUtc(), e.getOffsetColumn() }) {
assertThat(o.toInstant()).isEqualTo(MOMENT);
}
// NORMALIZE stores a zone-less timestamp in the *writer's* JVM zone, so it keeps the instant
// only when the reading JVM has the same default zone as the writing JVM -- unless direct
// JDBC handling is on, which (observed) bypasses the normalisation altogether.
boolean sameZone = !Db.phase().equals("read")
|| System.getProperty("dt.writerZone").equals(ZoneId.systemDefault().getId());
assertThat(e.getOffsetNormalize().toInstant().equals(MOMENT)).isEqualTo(sameZone || Db.directJdbc());
// Offset identity. H2's TIMESTAMP WITH TIME ZONE keeps the offset; PostgreSQL's timestamptz stores
// only the instant, so NATIVE storage comes back expressed in UTC. COLUMN keeps the offset
// in a companion column on both.
ZoneOffset kolkataOffset = ZoneOffset.ofHoursMinutes(5, 30);
ZoneOffset nativeOffset = Db.kind().equals("postgres") ? ZoneOffset.UTC : kolkataOffset;
assertThat(e.getOffsetNative().getOffset()).isEqualTo(nativeOffset);
assertThat(e.getOffsetDefault().getOffset()).isEqualTo(nativeOffset);
assertThat(e.getOffsetColumn().getOffset()).isEqualTo(kolkataOffset);
if (!Db.directJdbc()) {
assertThat(e.getOffsetNormalizeUtc().getOffset()).isEqualTo(ZoneOffset.UTC);
}
}
}
static String row(String type, Object in, Object out, String raw) {
String same = "n/a ";
if (in instanceof OffsetDateTime a && out instanceof OffsetDateTime b) {
same = String.valueOf(a.toInstant().equals(b.toInstant())) + (a.toInstant().equals(b.toInstant()) ? "" : " ");
}
else if (in instanceof Instant) {
same = String.valueOf(in.equals(out)) + (in.equals(out) ? "" : " ");
}
return String.format("%-29s out %-27s | equals %-5s | same instant %-5s | raw %s", type, out,
in.equals(out), same, raw);
}
}
@@ -0,0 +1,56 @@
package com.ankurm.datetime;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
/** Collects lines and writes output/NN-name-<db>-<jvm zone>[-<variant>]-<h7|h8>.txt. */
final class Transcript {
static final String LABEL = System.getProperty("h.label", "h7");
static final String VERSION = System.getProperty("h.version", "?");
private final List<String> lines = new ArrayList<>();
private final Path file;
Transcript(String name, String variant, String dbProduct) {
String zone = TimeZone.getDefault().getID().replace('/', '_');
String direct = System.getProperty("dt.directJdbc", "default");
String suffix = direct.equals("default") ? "" : "-direct" + direct;
this.file = Path.of("output", name + "-" + Db.kind() + "-" + zone
+ (variant.isEmpty() ? "" : "-" + variant) + suffix + "-" + LABEL + ".txt");
line("# " + name + (variant.isEmpty() ? "" : " (" + variant + ")"));
line("# Hibernate ORM " + VERSION + ", JDK " + Runtime.version().feature()
+ ", database " + dbProduct + ", JVM default zone " + TimeZone.getDefault().getID()
+ ", java_time_use_direct_jdbc " + Db.directJdbc() + (direct.equals("default") ? " (default)" : " (set)"));
}
static String product(Connection c) {
try {
return c.getMetaData().getDatabaseProductName() + " " + c.getMetaData().getDatabaseProductVersion();
}
catch (SQLException ex) {
throw new IllegalStateException(ex);
}
}
Transcript line(String s) {
lines.add(s);
return this;
}
void write() {
try {
Files.createDirectories(file.getParent());
Files.write(file, lines);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
}
@@ -0,0 +1,91 @@
package com.ankurm.datetime;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.*;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/** Same-JVM checks of the questions readers ask: @Column precision, java.util.Date, Year/YearMonth/Duration. */
class TypesTest {
@BeforeAll
static void needDatabase() {
Assumptions.assumeTrue(Db.available(), "dt.db=postgres but dt.pg.url is not set");
Assumptions.assumeTrue(!Db.phase().equals("read") && !Db.phase().equals("write"));
}
static List<String> columnTypes(Session s, String table) {
return s.doReturningWork(c -> {
List<String> out = new ArrayList<>();
try (Statement st = c.createStatement();
ResultSet rs = st.executeQuery("select column_name, data_type, datetime_precision from information_schema.columns "
+ "where lower(table_name) = '" + table + "' and lower(table_schema) = 'public' order by ordinal_position")) {
while (rs.next()) {
out.add(String.format("%-26s %-28s precision %s", rs.getString(1).toLowerCase(), rs.getString(2).toLowerCase(),
rs.getString(3)));
}
}
return out;
});
}
@Test
void columnPrecisionAttributes() {
LocalDateTime in = LocalDateTime.of(2026, 6, 15, 14, 0, 0, 123_456_789);
try (SessionFactory sf = Db.open(true, Map.of(), PrecisionEvent.class)) {
sf.inTransaction(s -> s.persist(new PrecisionEvent(1L, in)));
try (Session s = sf.openSession()) {
PrecisionEvent out = s.find(PrecisionEvent.class, 1L);
Transcript t = new Transcript("08-column-precision", "", s.doReturningWork(Transcript::product));
t.line("# written: " + in + " (nanos .123456789); generated column types, then what came back");
columnTypes(s, "precision_event").stream().filter(l -> !l.startsWith("id ")).forEach(t::line);
t.line("default -> " + out.getDefaultPrecision());
t.line("precision = 9 -> " + out.getPrecision9());
t.line("secondPrecision = 9 -> " + out.getSecondPrecision9());
t.line("secondPrecision = 3 -> " + out.getSecondPrecision3());
t.line("Instant, secondPrecision = 9 -> " + out.getInstantSecondPrecision9());
t.write();
// secondPrecision = 3 keeps milliseconds only, whatever the database
assertThat(out.getSecondPrecision3().getNano()).isEqualTo(123_000_000);
// precision = 9 changes nothing relative to the default
assertThat(out.getPrecision9()).isEqualTo(out.getDefaultPrecision());
}
}
}
@Test
void legacyAndYearTypes() {
Date now = Date.from(Instant.parse("2026-06-15T08:30:00Z"));
try (SessionFactory sf = Db.open(true, Map.of(), Legacy.class)) {
sf.inTransaction(s -> s.persist(new Legacy(1L, now, Year.of(2026), YearMonth.of(2026, 6), Duration.ofMinutes(90))));
try (Session s = sf.openSession()) {
Legacy out = s.find(Legacy.class, 1L);
Transcript t = new Transcript("09-legacy-types", "", s.doReturningWork(Transcript::product));
t.line("# java.util.Date with no @Temporal, Year, YearMonth, Duration: generated column types and round trip");
columnTypes(s, "legacy").stream().filter(l -> !l.startsWith("id ")).forEach(t::line);
t.line("java.util.Date in " + now.toInstant() + " | out " + out.getUtilDate().toInstant() + " | class " + out.getUtilDate().getClass().getName());
t.line("java.util.Date in.equals(out) " + now.equals(out.getUtilDate()) + " | out.equals(in) " + out.getUtilDate().equals(now));
t.line("Year in 2026 | out " + out.getYear());
t.line("YearMonth in 2026-06 | out " + out.getYearMonth());
t.line("Duration in PT1H30M | out " + out.getDuration());
t.write();
assertThat(out.getUtilDate().toInstant()).isEqualTo(now.toInstant());
assertThat(out.getUtilDate()).isInstanceOf(java.sql.Timestamp.class);
assertThat(now.equals(out.getUtilDate())).isTrue();
assertThat(out.getUtilDate().equals(now)).isFalse();
assertThat(out.getYear()).isEqualTo(Year.of(2026));
assertThat(out.getYearMonth()).isEqualTo(YearMonth.of(2026, 6));
assertThat(out.getDuration()).isEqualTo(Duration.ofMinutes(90));
}
}
}
}
@@ -0,0 +1,117 @@
package com.ankurm.datetime;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.jupiter.api.*;
import java.sql.ResultSet;
import java.sql.Statement;
import java.time.*;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/**
* ZonedDateTime on its own: what a named zone turns into, and the driver combination where it cannot
* be bound or read at all (PostgreSQL JDBC + java_time_use_direct_jdbc=true).
*/
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class ZonedTest {
static final Instant MOMENT = Instant.parse("2026-06-15T08:30:00Z");
static final ZonedDateTime PARIS = ZonedDateTime.of(LocalDateTime.of(2026, 6, 15, 10, 30), ZoneId.of("Europe/Paris"));
/**
* pgjdbc 42.7.x has no ZonedDateTime support for getObject/setObject. Hibernate 7.4 with direct JDBC
* switched on hands it the value anyway; the Hibernate 8 beta falls back to the legacy conversion.
*/
static boolean pgDirect() {
return Db.kind().equals("postgres") && Db.directJdbc() && Transcript.LABEL.equals("h7");
}
@BeforeAll
static void needDatabase() {
Assumptions.assumeTrue(Db.available(), "dt.db=postgres but dt.pg.url is not set");
}
@Test
@Order(1)
void write() {
Assumptions.assumeTrue(!Db.phase().equals("read"));
try (SessionFactory sf = Db.open(true, Map.of(), ZonedEvent.class)) {
ZonedEvent e = new ZonedEvent(1L);
e.setZonedDefault(PARIS);
e.setZonedColumn(PARIS);
if (!pgDirect()) {
sf.inTransaction(s -> s.persist(e));
return;
}
// Expected failure #1: binding.
Transcript t;
try (Session s = sf.openSession()) {
t = new Transcript("04-zoned-failure", "", s.doReturningWork(Transcript::product));
}
t.line("# ZonedDateTime on PostgreSQL with java_time_use_direct_jdbc=true");
t.line("## persist(new ZonedEvent(zonedDefault = " + PARIS + "))");
RuntimeException bind = org.junit.jupiter.api.Assertions.assertThrows(RuntimeException.class,
() -> sf.inTransaction(s -> s.persist(e)));
chain(t, bind);
// Expected failure #2: reading, even a row whose ZonedDateTime columns are NULL.
sf.inTransaction(s -> s.doWork(c -> {
try (Statement st = c.createStatement()) {
st.executeUpdate("insert into zoned_event (id) values (2)");
}
}));
t.line("## find(ZonedEvent.class, 2) -- a row whose ZonedDateTime columns are NULL");
RuntimeException read = org.junit.jupiter.api.Assertions.assertThrows(RuntimeException.class,
() -> sf.inTransaction(s -> s.find(ZonedEvent.class, 2L)));
chain(t, read);
t.write();
}
}
@Test
@Order(2)
void read() {
Assumptions.assumeTrue(!Db.phase().equals("write"));
Assumptions.assumeTrue(!pgDirect(), "bind and read failures are recorded by write(), see 04-zoned-failure");
try (SessionFactory sf = Db.open(false, Map.of(), ZonedEvent.class); Session s = sf.openSession()) {
String product = s.doReturningWork(Transcript::product);
ZonedEvent e = s.find(ZonedEvent.class, 1L);
String[] raw = s.doReturningWork(c -> {
try (Statement st = c.createStatement();
ResultSet rs = st.executeQuery("select cast(zdt_default_col as varchar), "
+ "cast(zdt_column_col as varchar) from zoned_event where id = 1")) {
rs.next();
return new String[] { rs.getString(1), rs.getString(2) };
}
});
String writer = System.getProperty("dt.writerZone", "?").replace('/', '_');
String variant = Db.phase().equals("read") ? "written-in-" + writer : "same-jvm";
Transcript t = new Transcript("04-zoned", variant, product);
t.line("# written: " + PARIS + " (instant " + MOMENT + ")");
t.line(row("ZonedDateTime default", e.getZonedDefault(), raw[0]));
t.line(row("ZonedDateTime COLUMN", e.getZonedColumn(), raw[1]));
t.write();
assertThat(e.getZonedDefault().toInstant()).isEqualTo(MOMENT);
assertThat(e.getZonedColumn().toInstant()).isEqualTo(MOMENT);
// A named zone never comes back: Europe/Paris is gone, only an offset or the JVM zone remains.
assertThat(e.getZonedDefault().getZone()).isNotEqualTo(ZoneId.of("Europe/Paris"));
assertThat(e.getZonedColumn().getZone()).isNotEqualTo(ZoneId.of("Europe/Paris"));
}
}
private static String row(String type, ZonedDateTime out, String raw) {
return String.format("%-22s out %-32s | equals %-5s | same instant %-5s | zone %-16s | raw %s", type, out,
PARIS.equals(out), PARIS.toInstant().equals(out.toInstant()), out.getZone(), raw);
}
private static void chain(Transcript t, Throwable ex) {
Throwable c = ex;
while (c != null) {
t.line(c.getClass().getName() + ": " + String.valueOf(c.getMessage()).replace("\n", " "));
c = c.getCause();
}
}
}