如何使用 hibernate 在 SQL 服务器数据库中存储 joda DateTime
How to store joda DateTime in SQL Server database with hibernate
我在使用 hibernate 和 joda time 将 DateTime 存储在数据库中时遇到奇怪的问题。
我有一个这样的豆子:
import org.joda.time.DateTime;
public class RelationshipEntity {
@Column(name = "date_revision")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime dateRevision;
// other fields
}
我在 TimeZone.setDefault(TimeZone.getTimeZone("Europe/Paris"));
的应用程序中将时区设置为 Europe/Paris (GMT+1)
如果我将修订日期为 2017-01-19 13:24
的实体保存到数据库中,我可以看到数据库中的日期已设置为 2017-01-19 12:24
,但我不明白为什么。
数据库时区似乎也是 Europe/Paris 因为:
SELECT SYSDATETIME(); //2017-01-19 14:41
SELECT SYSUTCDATETIME(); // 2017-01-19 13:41
当我使用 spring-boot 时,我尝试在 application.yml
中添加这些属性
jadira.usertype.autoRegisterUserTypes: true
jadira.usertype.databaseZone: jvm
jadira.usertype.javaZone: jvm
并使用参数 -Duser.timezone=Europe/Paris
启动应用程序,但它仍将 UTC 日期保存到数据库中。
为了解决问题,我将 DateTime
更改为 LocalDateTime
:
@Column(name = "date_revision")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private DateLocalTime dateRevision;
进行此更改后,数据库中的 dateRevision 与我在 java bean 中设置的相同。
有人能解释一下为什么当我使用类型 org.joda.time.DateTime
时它会将日期转换为 UTC 吗?
注意:我使用 Hibernate 4 和 joda-time 2.5
这是因为 zoda DateTime 以 UTC 格式存储数据库中的日期,而 LocalDateTime 按原样存储日期,当您不关心时区时应该使用它。
在 DateTime 的情况下,当您需要考虑时区(夏令时等)时,它会以这种方式处理它并以世界时存储日期。
请参阅此answer了解详细信息。
我在使用 hibernate 和 joda time 将 DateTime 存储在数据库中时遇到奇怪的问题。
我有一个这样的豆子:
import org.joda.time.DateTime;
public class RelationshipEntity {
@Column(name = "date_revision")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime dateRevision;
// other fields
}
我在 TimeZone.setDefault(TimeZone.getTimeZone("Europe/Paris"));
如果我将修订日期为 2017-01-19 13:24
的实体保存到数据库中,我可以看到数据库中的日期已设置为 2017-01-19 12:24
,但我不明白为什么。
数据库时区似乎也是 Europe/Paris 因为:
SELECT SYSDATETIME(); //2017-01-19 14:41
SELECT SYSUTCDATETIME(); // 2017-01-19 13:41
当我使用 spring-boot 时,我尝试在 application.yml
jadira.usertype.autoRegisterUserTypes: true
jadira.usertype.databaseZone: jvm
jadira.usertype.javaZone: jvm
并使用参数 -Duser.timezone=Europe/Paris
启动应用程序,但它仍将 UTC 日期保存到数据库中。
为了解决问题,我将 DateTime
更改为 LocalDateTime
:
@Column(name = "date_revision")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private DateLocalTime dateRevision;
进行此更改后,数据库中的 dateRevision 与我在 java bean 中设置的相同。
有人能解释一下为什么当我使用类型 org.joda.time.DateTime
时它会将日期转换为 UTC 吗?
注意:我使用 Hibernate 4 和 joda-time 2.5
这是因为 zoda DateTime 以 UTC 格式存储数据库中的日期,而 LocalDateTime 按原样存储日期,当您不关心时区时应该使用它。
在 DateTime 的情况下,当您需要考虑时区(夏令时等)时,它会以这种方式处理它并以世界时存储日期。
请参阅此answer了解详细信息。