2017-10-06 48 views
0

我在DAO添加了這個:與返回的對象JPA @Query問題

@Query("SELECT distinct LBL.cId, LBL from FooBar LBL ORDER BY LBL.collectedAt DESC") 
    List<FooBar> findDistinctcIdOrderByCollectedAtDesc(); 

然後這是我的服務

List<FooBar> fooBars = this.liveBusLocationDao.findDistinctcIdOrderByCollectedAtDesc(); 

這是我得到了什麼,當我調試內容fooBars

fooBars = {[email protected]} size = 1 
0 = {Object[2]@11093} 
    0 = "string" 
    1 = {[email protected]} "FooBar(cId=string, internalcId=123456789012, createdAt=2011-11-02 02:59:12.208, collectedAt=2017-10-06 14:26:26.544)" 

如何遍歷此結果?

+0

這是春天的數據JPA不是JPA API。即沒有這樣的'JPA @ Query'。也許正確標記你的問題 – DN1

回答

0

您的查詢正在請求2個屬性。 你可以做一個自定義類,作爲id和對象,或者你可以只從SELECT

刪除 LBL.cId

你的要求應該是:

@Query("SELECT distinct LBL from FooBar LBL ORDER BY LBL.collectedAt DESC") 
List<FooBar> findDistinctcIdOrderByCollectedAtDesc(); 

的不同的工作對整個行。看看吧,如果你不舒爾的話,你可以使用group by LBL

https://stackoverflow.com/a/10066187/3543153

+0

但是這個查詢會給我什麼結果呢?在哪個列上應用了不同的條件? – nirvair

+0

我更新了我的答案。在整個行上不同的工作。你也可以用一個組代替不同的組 – DamienB

0

您將需要創建一個結果類,如果你想使用投影而無需使用特殊的語法在JPA查詢得到Object[]的結果。

package com.example 

class ResultClass{ 

    int fieldOne; 
    String fieldTwo; 

    public (int fieldOne, intfieldTwo){ 
    // .. set fields 
    } 

} 

和查詢:

@Query("SELECT distinct new com.example.ResultClass(LBL.cId, LBL.strProperty) from FooBar LBL ORDER BY LBL.collectedAt DESC") 
    List<ResultClass> findDistinctcIdOrderByCollectedAtDesc();