|
| 1 | +/* |
| 2 | + * SPDX-License-Identifier: LGPL-2.1-or-later |
| 3 | + * Copyright Red Hat Inc. and Hibernate Authors |
| 4 | + */ |
| 5 | +package org.hibernate.orm.test.instant; |
| 6 | + |
| 7 | +import jakarta.persistence.Entity; |
| 8 | +import jakarta.persistence.Id; |
| 9 | +import org.hibernate.annotations.JdbcTypeCode; |
| 10 | +import org.hibernate.testing.orm.junit.EntityManagerFactoryScope; |
| 11 | +import org.hibernate.testing.orm.junit.Jpa; |
| 12 | +import org.junit.jupiter.api.Test; |
| 13 | + |
| 14 | +import java.time.Instant; |
| 15 | +import java.time.LocalDateTime; |
| 16 | +import java.time.OffsetDateTime; |
| 17 | +import java.time.ZoneOffset; |
| 18 | + |
| 19 | +import static org.hibernate.type.SqlTypes.TIMESTAMP; |
| 20 | +import static org.hibernate.type.SqlTypes.TIMESTAMP_WITH_TIMEZONE; |
| 21 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 22 | + |
| 23 | +@Jpa(annotatedClasses = InstantTest.Instants.class) |
| 24 | +public class InstantTest { |
| 25 | + @Test |
| 26 | + public void test(EntityManagerFactoryScope scope) { |
| 27 | + Instant now = Instant.now(); |
| 28 | + ZoneOffset zone = ZoneOffset.ofHours(1); |
| 29 | + scope.getEntityManagerFactory() |
| 30 | + .runInTransaction( entityManager -> { |
| 31 | + Instants instants = new Instants(); |
| 32 | + instants.instantInUtc = now; |
| 33 | + instants.instantInLocalTimeZone = now; |
| 34 | + instants.instantWithTimeZone = now; |
| 35 | + instants.localDateTime = LocalDateTime.ofInstant( now, zone ); |
| 36 | + instants.offsetDateTime = OffsetDateTime.ofInstant( now, zone ); |
| 37 | + instants.localDateTimeUtc = LocalDateTime.ofInstant( now, ZoneOffset.UTC ); |
| 38 | + instants.offsetDateTimeUtc = OffsetDateTime.ofInstant( now, ZoneOffset.UTC ); |
| 39 | + entityManager.persist( instants ); |
| 40 | + } ); |
| 41 | + scope.getEntityManagerFactory() |
| 42 | + .runInTransaction( entityManager -> { |
| 43 | + Instants instants = entityManager.find( Instants.class, 0 ); |
| 44 | + assertEquals( now, instants.instantInUtc ); |
| 45 | + assertEquals( now, instants.instantInLocalTimeZone ); |
| 46 | + assertEquals( now, instants.instantWithTimeZone ); |
| 47 | + assertEquals( now, instants.offsetDateTime.toInstant() ); |
| 48 | + assertEquals( now, instants.localDateTime.toInstant( zone ) ); |
| 49 | + assertEquals( now, instants.offsetDateTimeUtc.toInstant() ); |
| 50 | + assertEquals( now, instants.localDateTimeUtc.toInstant( ZoneOffset.UTC ) ); |
| 51 | + } ); |
| 52 | + } |
| 53 | + @Entity |
| 54 | + static class Instants { |
| 55 | + @Id long id; |
| 56 | + Instant instantInUtc; |
| 57 | + @JdbcTypeCode(TIMESTAMP) Instant instantInLocalTimeZone; |
| 58 | + @JdbcTypeCode(TIMESTAMP_WITH_TIMEZONE) Instant instantWithTimeZone; |
| 59 | + LocalDateTime localDateTime; |
| 60 | + OffsetDateTime offsetDateTime; |
| 61 | + LocalDateTime localDateTimeUtc; |
| 62 | + OffsetDateTime offsetDateTimeUtc; |
| 63 | + } |
| 64 | +} |
0 commit comments