2014-03-12 86 views
0

因此,由於Ebean不支持其他許多事情中的集合函數,所以我試圖讓我的複雜查詢使用RawSql工作。此外,事實證明,我需要使用.unparsed(sql)作爲我的有效查詢字符串不會與.parse(sql)Ebean RawSql未分析的查詢

這裏是我的代碼:

final String sql = "SELECT DISTINCT d.user_id, CAST(d.date as DATE) AS date," + 
      " MAX(d.speed_KPH) OVER (PARTITION BY CAST(d.date as DATE)) AS maxSpeed," + 
      " AVG(d.speed_KPH) OVER (PARTITION BY CAST(d.date as DATE)) AS avgSpeed" + 
      " FROM Driver as d" + 
      " WHERE d.date BETWEEN '" + sdf.format(from) + "' and '" + sdf.format(to) + "'" + 
      " ORDER BY date DESC"; 

final RawSql rawSql = RawSqlBuilder.unparsed(sql) 
     .columnMapping("user_id", "user.userId") 
     .columnMapping("date", "message.date") 
     .columnMapping("maxSpeed", "maxSpeed") 
     .columnMapping("avgSpeed", "avgSpeed") 
     .create(); 

final List<MessageAggregate> theList = Ebean.find(MessageAggregate.class).setRawSql(rawSql) 
     .findList(); 

Ebean產生以下的(有效)查詢:

SELECT DISTINCT d.user_id, CAST(d.date as DATE) AS date, 
     MAX(d.speed_KPH) OVER (PARTITION BY CAST(d.date as DATE)) AS maxSpeed, 
     AVG(d.speed_KPH) OVER (PARTITION BY CAST(d.date as DATE)) AS avgSpeed 
    FROM Driver AS d 
    WHERE d.date 
    BETWEEN '2014-01-02 09:00:00' and '2014-03-12 17:00:00' 
    ORDER BY date DESC 

其中在MSSQL Studio中運行時產生:

user_id date maxSpeed avgSpeed 
4 2014-02-20 74.1 1.1935294117647 
311 2014-02-20 74.1 1.1935294117647 
314 2014-02-20 74.1 1.1935294117647 
347 2014-02-20 74.1 1.1935294117647 
... etc ... 

當運行Ebean(通過PlayFramework 2.2.2):

Caused by: javax.persistence.PersistenceException: Query threw SQLException:Invalid column index 0. 
Bind values:[] 

我曾嘗試與不使用.columnMapping,發現這個小(3+歲金塊here),這意味着您可以使用.columnMapping(),但他們必須在正確的,線性順序,在我的情況,他們是。

+0

正如你旁邊你問通過Ebean谷歌組的幫助?這看起來更像是一個問題而不是問題? –

回答

0

目前沒有辦法做到這一點。對聚合函數的支持不在那裏。所以我最終簡化了查詢,並通過代碼(Java)完成了其他結果過濾。如果你遇到類似的情況,不要浪費你的時間(和你的頭髮!)試圖使這個東西工作,因爲它不會。

+0

我被困在現在拉着我的頭髮的一步。你有沒有發現任何記錄說聚合功能不被支持?我不能設法得到一個最大()工作 –

+0

我絕對不能讓他們任何工作。唯一的記錄來自ebean論壇,其他人發佈類似問題。我最終不得不放棄,並在Java中進行大部分的處理。更慢,是的,但它必須完成。 –