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

查看:236
本文介绍了如何将时间戳列映射到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().

当我使用此表的Entity类获取数据时,就会出现问题. 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(),而是用@PrePersist在JPA中将其表示为:

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没有使用数据库中应用的默认值进行更新.认为该值仍为null会卡住.

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天全站免登陆