2016-09-08 144 views
1

我有一個數據庫,其中包含所有與日期相關的各種值。我想要做的是返回地圖的日期和與日期相關的所有值的平均值。每次我提出一個要求,我得到如下回應:Spring data jpa - 返回地圖

{ 
    "timestamp": 1473327111738, 
    "status": 500, 
    "error": "Internal Server Error", 
    "exception": "org.springframework.dao.IncorrectResultSizeDataAccessException", 
    "message": "result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException: result returns more than one elements", 
    "path": "/dailyAverage" 
} 

我的代碼:

@Query("SELECT du.date, avg(du.usage) FROM DataUsageModel du WHERE du.date BETWEEN :start_time AND :end_time GROUP BY day(du.date)") 
Map<String, Double> findDailyAverages(@Param("start_time") LocalDateTime startTime, @Param("end_time") LocalDateTime endTime); 
+0

嘗試使List >作爲返回類型 – nowszy94

回答

1

你有上面什麼是JSON對象。必須有調用findDailyAverages方法並將其轉換爲Json對象的代碼。如果你不想改變然後解析的JSONObject(以上你的回答),並創建的HashMap

public static void jsonToMap(String t) throws JSONException { 

    HashMap<String, String> map = new HashMap<String, String>(); 
    JSONObject jObject = new JSONObject(t); 
    Iterator<?> keys = jObject.keys(); 

    while(keys.hasNext()){ 
     String key = (String)keys.next(); 
     String value = jObject.getString(key); 
     map.put(key, value); 

    } 

    System.out.println("json : "+jObject); 
    System.out.println("map : "+map); 
} 
0

創建新模式(DataModal)與DataModal選定字段構造 例

class DataModal{ 
    Date date; 
    Float usage; 
    DataModal(Date date, Float usage){ 
    this.date=date; 
    this.usage=usage; 
    } 
} 



@Query("SELECT new DataModal(du.date, avg(du.usage) as usage) FROM  DataUsageModel du WHERE du.date BETWEEN :start_time AND :end_time GROUP BY day(du.date)") 

這個返回值作爲列表

+0

最新的問題是什麼? – kmera