Ngu*_*aga 28 postgresql hibernate jpa jpa-2.0
我有一个JPA 2应用程序(使用Hibernate 3.6作为JPA实现)使用Postgresql(使用9.0-801.jdbc3 JDBC驱动程序).
我无法将"timestamp with time zone"字段映射到我的JPA实体.
这是一个例子:
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 )
)
Run Code Online (Sandbox Code Playgroud)
我试图映射如下:
@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 */
Run Code Online (Sandbox Code Playgroud)
我继续使用以下根本原因获取异常: Caused by: org.hibernate.HibernateException: Wrong column type in public.backend_themetopic for column created. Found: timestamptz, expected: date
我试过了什么
java.util.Calendar有java.util.Date-没有什么区别java.sql.Timestamp- 抱怨我无法将@Temporal注释应用于Timestamporg.joda.time.DateTime自定义@Type注释(@Type(type="org.joda.time.contrib.hibernate.PersistentDateTimeTZ"))也无效约束
我的问题是:我应该如何将这些时区感知时间戳映射到我的JPA实体中?
我最终通过关闭模式验证来实现这种"工作" - 以一种黑客的方式.
以前,我有<property name="hibernate.hbm2ddl.auto" value="validate"/>"hibernate.hbm2ddl.auto"我的persistence.xml.当我注释掉这个属性时,我的应用服务器启动了,模型"工作"了.
我的实体的最终形式是:
@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 */
Run Code Online (Sandbox Code Playgroud)
在阅读了相当多的内容之后,我得到的印象是,没有简单的方法将Postgresql时间戳映射到时区列.
一些JPA实现+数据库组合本身支持这一点(EclipseLink + Oracle就是一个例子).对于hibernate,使用jodatime扩展,可以使用正常时间戳和时区的varchar字段存储时区感知时间戳(我不能这样做,因为我受限于更改数据库模式).Jadira用户类型或完全自定义用户类型也可用于解决此问题.
我需要注意的是,我对这个实体的用例是"只读",所以我可以摆脱看似天真的"解决方案".
加 @Column(columnDefinition= "TIMESTAMP WITH TIME ZONE")
@Column(name = "run_from", columnDefinition= "TIMESTAMP WITH TIME ZONE")
@NotNull
@Temporal(TemporalType.TIMESTAMP)
private Date runFrom;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27338 次 |
| 最近记录: |