2011-12-01 84 views
0

我是Java noob,在Spring中工作,使用我定製的Roo生成的模型。JPL休眠日期數學

我需要選擇在X天內具有「maturationDate」的特定類型(本例中爲租賃)的記錄。爲了顯示目的,我創建了一個@Transient屬性,做數學題:

@Transient 
private Integer daysToMaturation; 

@PostLoad 
public void postLoad() { 
    Calendar calendar1 = Calendar.getInstance(); 
    Calendar calendar2 = Calendar.getInstance(); 

    calendar2.setTime(this.getMaturesDate()); 
    calendar1.setTime(new Date()); 

    long milis1 = calendar1.getTimeInMillis(); 
    long milis2 = calendar2.getTimeInMillis(); 

    long day = milis2 - milis1; 

    Double diffDays = Math.ceil(day/(24 * 60 * 60 * 1000)); 

    this.daysToMaturation = diffDays.intValue(); 
} 

這不好吧輸出,但現在我需要找到所有記錄daysToMaturation < =什麼的,顯然這家酒店不直到查詢後才存在。

JPQL的日期函數是悲慘的原始的。如果我可以得到原始的SQL(可能在@Formula字段中),我可以用一行代碼來解決這個問題。我真正想要的是這樣說的能力:

@Formula("(select datediff(maturesDate, CURRENT_DATE())") 
private Integer daysToMaturation; 

...但失敗了,大概是因爲我不是說datediff()到MySQL,我說它JPA,從未聽說過它。它拋出以下異常:

org.hibernate.exception.SQLGrammarException: could not execute query; nested 
exception is javax.persistence.PersistenceException: 
org.hibernate.exception.SQLGrammarException: could not execute query 

和Hibernate的記錄下面一行:

ERROR org.hibernate.util.JDBCExceptionReporter - You have an error in your SQL 
syntax; check the manual that corresponds to your MySQL server version for the 
right syntax to use near '' at line 1 
+0

我認爲如果您使用EclipseLink> = 2.1(而不是Hibernate),則可以使用t他用'FUNC()'函數來調用JPQL規範中沒有定義的任何數據庫函數。 –

回答

0

雖然我同意日期數學函數在JPQL是原始的,這個問題可以很容易地通過計算對應日期規避你的「無論」延遲,並將數據庫中存儲的日期與此計算日期進行比較:

int daysToMaturation = 10; 
Date maxDate = addDaysToCurrentDate(daysToMaturation); 
String jpql = "select lease from Lease lease where lease.maturationDate <= :maxDate"; 
// ... 
+0

我明白了。我正在以某種方式將其整合到我在這裏的整個框架中。 Btw ...是「addDaysToCurrentDate()」一個真實的東西,還是那個僞代碼? –

+0

這是僞代碼。它的實現應該類似於你的postLoad方法 –