2009-07-11 114 views
0

我有以下字段定义在我的JPA实体之一:JPQL和时间戳与时区

@Column(nullable = false, name = "start_time", 
columnDefinition= "TIMESTAMP WITH TIME ZONE") 
@Temporal(javax.persistence.TemporalType.TIMESTAMP) 
private Date startTime = new Date(); 

@Column(nullable = true, name = "end_time", 
columnDefinition= "TIMESTAMP WITH TIME ZONE") 
@Temporal(javax.persistence.TemporalType.TIMESTAMP) 
private Date endTime = null; 

该数据库PostgreSQL和使用时间戳没有时区是不是一种选择。关于时区的插入和更新都很顺利。当我尝试在某些测试数据上运行SELECT JPQL查询并且过滤器参数是Date对象时,出现问题(至少我是这么认为的)。 OpenJPA生成的查询不包含参数中的时区。 任何人都可以给我一些关于JPA和timezone列的指导吗?

回答

0

我将避免在JPA实体中存储数据库时使用日期和日历。 标准 JDBC时间值没有时间戳的概念。

我用下面的风格,而不是

private Long effectiveDate; 
public Date getEffectiveDate() { 
    if (effectiveDate == null) { return null; } 
    return new Date(effectiveDate); 
} 
public void setEffectiveDate(Date d) { 
    if (d == null) { effectiveDate = null; } 
    effectiveDate = d.getTime(); 
} 

有效的是被存储在数据库中的数据是一个简单的长值。但是,在应用程序层中,仍然使用具有时区概念的Date对象。

现在有时您仍然希望将查询日期存储在数据库级别。在这种情况下,您可以执行以下操作:

private Long effectiveDate; 
private Date effectiveDateDate; 
public Date getEffectiveDate() { 
    if (effectiveDate == null) { return null; } 
    return new Date(effectiveDate); 
} 
public void setEffectiveDate(Date d) { 
    effectiveDateDate = d; 
    if (d == null) { effectiveDate = null; } 
    effectiveDate = d.getTime(); 
}