java 如何在h2数据库中存储时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39685463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:33:56  来源:igfitidea点击:

How to store timestamp in h2 database

javahibernateh2

提问by Smajl

I have a simple REST Api exposing several entities, some of which, has date field which I would like to store in a H2 database in the UNIX timestamp format. However, this is causing the followign exceptions:

我有一个简单的 REST Api,它公开了几个实体,其中一些实体具有我想以 UNIX 时间戳格式存储在 H2 数据库中的日期字段。但是,这会导致以下异常:

Caused by: org.h2.jdbc.JdbcSQLException: Cannot parse "TIMESTAMP" constant "335923000"; SQL statement:
INSERT INTO people (person_id, first_name, last_name, email, gender, location, date_birth) VALUES 
    ('1', 'Peter', 'Smith', '[email protected]', 'MALE', 'London', 335923000),
    ...

Previously, it worked with timestamp in the following format: '1980-04-08'.

以前,它使用以下格式的时间戳:'1980-04-08'.

This is the SQL table definition:

这是 SQL 表定义:

CREATE TABLE people (
    person_id BIGINT PRIMARY KEY auto_increment,
    first_name VARCHAR(32),
    last_name VARCHAR(32),
    email VARCHAR(128) UNIQUE,
    gender VARCHAR(8),
    location VARCHAR(32),
    date_birth TIMESTAMP,
);

and my mapping object (unnecessary details omitted):

和我的映射对象(省略了不必要的细节):

@Entity
@Table(name = "people")
@Getter
@Setter
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "person_id")
    private long id;

    ...

    @Column(name = "date_birth")
    @JsonFormat(pattern = "YYYY-MM-dd")
    private Date dateOfBirth;

    ...
}

I assume the the @JsonFormatannotation does not have anything to do with the database timestamp format but I am not sure how to tell hibernate that my timestamp are in UNIX format.

我假设@JsonFormat注释与数据库时间戳格式没有任何关系,但我不确定如何告诉 hibernate 我的时间戳是 UNIX 格式。

I have looked at convert unix timestamp to H2 timestampand H2 docs and this standard format should be supported. Could someone point out to me, what am I doing wrong?

我已经看过将 unix 时间戳转换为 H2 时间戳和 H2 文档,并且应该支持这种标准格式。有人可以指出我,我做错了什么吗?

回答by Alex

well, the answer have been done in another manner here

好吧,答案在这里以另一种方式完成

you'll find a way to represent a datetime with milliseconds without timezone (that is what is "timestamp" is in SQL)

你会找到一种方法来表示没有时区的毫秒日期时间(这就是 SQL 中的“时间戳”)