2009-07-11 105 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(); 
}