如何将时间戳列映射到 JPA 类型? [英] How to map timestamp column to JPA type?

查看:31
本文介绍了如何将时间戳列映射到 JPA 类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Play!1.2.4 和 PostgreSQL 9.1.我创建了一个带有 created_at 列的表,类型为:timestamp without time zone.它的默认值是 now().

I'm using Play! 1.2.4 and PostgreSQL 9.1. I created a table with a created_at column, of type: timestamp without time zone. It has a default value of now().

当我使用我的实体类为这个表获取数据时,问题就出现了.createdAt 字段总是返回 null.这是字段定义:

The problem comes when I fetch data using my Entity class for this table. The createdAt field is always coming back null. Here is the field definition:

@Column(name="created_at", insertable=false)
public java.sql.Date createdAt;

所有其他字段均已正确填充.我尝试将字段类型更改为 DateCalendarTimestamp 等,并尝试添加 @Timestamp注释.但没有一个组合被证明是成功的.

All the other fields are populated correctly. I have tried changing the field type to a Date, Calendar, Timestamp, etc., and tried adding a @Timestamp annotation. But no combination has proved successful.

在此先感谢您的帮助!

作为参考,这里是我用来创建表的 DDL.

For reference, here is the DDL I used to create the table.

CREATE TABLE Users
(
  id serial     NOT NULL,
  username text NOT NULL,
  email text    NOT NULL,
  password_hash text NOT NULL DEFAULT 0,
  created_at timestamp without time zone DEFAULT now(),
  CONSTRAINT Users_pkey PRIMARY KEY (id),
  CONSTRAINT Users_username_key UNIQUE (username)
);

更新:我认为问题与使用 JPA 插入记录有关.数据库为 created_at 填充默认值 now(),但不知何故 Hibernate 在获取该行时并不知道它.

Update: I think the problem has to do with using JPA to insert a record. The database populates a default value of now() for created_at, but somehow Hibernate doesn't know about it when fetching that row.

如果我查询已存在的行,createdAt 字段将正确填充!好的...这缩小了问题的范围.

If I query for a row that already existed, the createdAt field is populated correctly! OK... this narrows down the problem.

推荐答案

我没有完全解决问题,但我已经解决了.

I didn't solve the problem exactly, but I worked around it.

我没有让数据库提供 now() 的默认值,而是在 JPA 中用 @PrePersist 表示:

Instead of having the database supply the default value of now(), I expressed it in JPA with @PrePersist:

@Column(name="created_at", nullable=false)
@Temporal(TemporalType.TIMESTAMP)
public Date createdAt;

@PrePersist
protected void onCreate() {
    createdAt = new Date();
}

效果很好!灵感来自这个答案.我仍然不确定为什么 Hibernate 没有使用数据库中应用的默认值进行更新.它被卡住了,认为该值仍然为空.

That works fine! Inspiration taken from this answer. I'm still not sure why Hibernate didn't get updated with the default value that was applied in the database. It was stuck thinking the value was still null.

这篇关于如何将时间戳列映射到 JPA 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆