我有一个正在运行的应用程序 spring boot 1.3 + hibernate 5 + java 8 + ZonedDateTime + postgresql 并且在其中一个表中我有以下字段。
@Column(name = "DATE_ENABLED")
@Type(type="java.time.ZonedDateTime")
private ZonedDateTime dateEnabled;
@Column(name = "DATE_DISABLED")
@Type(type="java.time.ZonedDateTime")
private ZonedDateTime dateDisabled;
如果我运行该应用程序,那么我会看到默认情况下会产生“没有时区的时间戳”
testDB=# \d type
Table "public.type"
Column | Type | Modifiers
--------------------------------+-----------------------------+-----------
type_id | bytea | not null
date_disabled | timestamp without time zone |
date_enabled | timestamp without time zone |
我知道如果我将 columnDefinition="TIMESTAMP WITH TIME ZONE" 添加到列中,即类似于
@Column(name = "DATE_DISABLED", columnDefinition= "TIMESTAMP WITH TIME ZONE")
然后它工作正常,我可以看到休眠创建了一个带有时区的列,但是如果我理解正确,这将只适用于 postgres,即如果我明天将数据库更改为 mysql,那么休眠将引发错误。
因此我的问题是一般如何做到这一点,即告诉休眠创建一个应该包含时区和偏移量的列。我的观点是,由于故意创建 Java 类型“ZonedDateTime”以包括时区和 UTC 时间偏移,那么休眠将默认创建一个包含时区的列。因此问题又来了:告诉休眠包含时区和偏移量的正确方法是什么。
这是我的pom的一部分:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.0.RELEASE</version>
<hibernate.version>5.0.4.Final</hibernate.version>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-java8</artifactId>
<version>${hibernate.version}</version>
</dependency>
和我的显示方言的属性文件
@Bean
public Properties hibernateProperties() {
return new Properties() {
{
setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
setProperty("hibernate.chach.provider_class", "org.hibernate.cache.NoCacheProvider");
setProperty("hibernate.show_sql", "true");
setProperty("hibernate.hbm2ddl.auto", "create-drop");
}
};
}