Hibernate 如何映射postgresql“;带时区的时间戳“;在JPA 2实体中
我有一个JPA2应用程序(Hibernate 3.6作为JPA实现),它使用Postgresql(带有9.0-801.jdbc3 JDBC驱动程序) 我无法将“时区时间戳”字段映射到我的JPA实体 以下是一个例子:Hibernate 如何映射postgresql“;带时区的时间戳“;在JPA 2实体中,hibernate,postgresql,jpa,jpa-2.0,Hibernate,Postgresql,Jpa,Jpa 2.0,我有一个JPA2应用程序(Hibernate 3.6作为JPA实现),它使用Postgresql(带有9.0-801.jdbc3 JDBC驱动程序) 我无法将“时区时间戳”字段映射到我的JPA实体 以下是一个例子: CREATE TABLE theme ( id serial NOT NULL, # Fields that are not material to the question have been edited out run_from timestamp with tim
CREATE TABLE theme
(
id serial NOT NULL,
# Fields that are not material to the question have been edited out
run_from timestamp with time zone NOT NULL,
run_to timestamp with time zone NOT NULL,
CONSTRAINT theme_pkey PRIMARY KEY (id ),
CONSTRAINT theme_name_key UNIQUE (name )
)
我已尝试绘制以下地图:
@Entity
@Table(schema = "content", name = "theme")
public class Theme extends AbstractBaseEntity {
private static final long serialVersionUID = 1L;
@Column(name = "run_from")
@NotNull
@Temporal(TemporalType.TIMESTAMP)
private Date runFrom;
@Column(name = "run_to")
@NotNull
@Temporal(TemporalType.TIMESTAMP)
private Date runTo;
/* The rest of the entity has been edited out */
我不断得到一个异常,其根本原因如下:由以下原因引起:org.hibernate.HibernateException:public.backend\u主题中创建的列的列类型错误。找到:timestamptz,预期:日期
我尝试过的
- 将
替换为java.util.Calendar
——没有任何区别java.util.Date
- 使用
-抱怨我无法将java.sql.Timestamp
注释应用于@Temporal
时间戳
- 使用带有自定义
注释(@Type
的@Type(Type=“org.joda.time.contrib.hibernate.PersistentDateTimeTZ”)
也不起作用org.joda.time.DateTime
- 此应用程序与“遗留系统”交互,因此,更改日期字段的类型不是一个好的选择
“hibernate.hbm2ddl.auto”
。当我注释掉这个属性时,我的应用程序服务器启动了,模型“工作”
我的实体的最终形式是:
@Entity
@Table(schema = "content", name = "theme")
public class Theme extends AbstractBaseEntity {
private static final long serialVersionUID = 1L;
@Column(name = "run_from", columnDefinition = "timestamp with time zone not null")
@NotNull
@Temporal(TemporalType.TIMESTAMP)
private Date runFrom;
@Column(name = "run_to", columnDefinition = "timestampt with time zone not null")
@NotNull
@Temporal(TemporalType.TIMESTAMP)
private Date runTo;
/* Getters, setters, .hashCode(), .equals() etc omitted */
在读了很多这方面的内容后,我得到的印象是,没有简单的方法可以将Postgresql时间戳映射为时区列
一些JPA实现+数据库组合本机支持这一点(EclipseLink+Oracle就是一个例子)。对于hibernate,使用jodatime扩展,可以使用时区的普通时间戳+varchar字段来存储时区感知的时间戳(我不能这样做,因为我被限制更改数据库模式)。或者完全自定义的用户类型也可以用来解决这个问题
我需要注意的是,我对这个实体的用例是“只读”的,所以我可以用一个看似幼稚的“解决方案”逃脱惩罚 添加@Column(columnDefinition=“带时区的时间戳”)
这实际上仅对DDL自动或在运行时有用吗?
columnDefinition
值仅在DDL中使用。但是,如果您的表列是使用该DDL创建的,那么它也会间接影响运行时行为的细节。
@Column(name = "run_from", columnDefinition= "TIMESTAMP WITH TIME ZONE")
@NotNull
@Temporal(TemporalType.TIMESTAMP)
private Date runFrom;