如何在 MySQL 中存储 Joda DateTime

How to store Joda DateTime in MySQL

我最近开始在我的测试项目中使用 Joda 时间库。 特别是我一直在享受 DateTime 的功能及其操作功能。

我的问题是如何在 MySql 中存储 DateTime。我正在为我的应用程序使用 Spring & Hibernate。

每当我尝试使用它时,我当前的实体都会抛出反序列化错误:

@Entity
@Table(name = "test_storage")
public class TestEntity {
    @Id @GeneratedValue
    private int id;

    @Column
    private DateTime testDate;

    //getters and setters
}

mysqltable结构如下:

Name: test_storage
Columns:
id         INT NOT_NULL, AUTO_INCREMENT
testDate   DATETIME

有什么建议吗?

DATETIME 是我的选择。在 and http://infopotato.com/blog/index/datetime_vs_timestamp

查看更多详细信息

如果您使用的是 Hibernate 4+,那么您可以采用 Jadira 用户类型,它允许您将 DateTime(以及其他与 JODA 日期时间相关的 class,如 LocalDate、LocalDateTime 等)映射到使用不同策略的数据库字段。

你的映射看起来像

public class TestEntity {
    //...

    @Column
    @Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
    private DateTime testDate;
}

阅读文档以了解如何正确使用这些类型以满足您的要求。

您可能很快会遇到的最大陷阱是,因为 Java 的日期不包含时区信息,也不坚持 UTC(JODA 的用户类型仍然需要在内部映射到 Timestamp/Date ),您可能需要确保您存储的方式确实提供了正确的信息。例如,将日期时间存储为 UTC,或者将时区信息存储为单独的字段等。