HaehnleinMar HaehnleinMar - 1 year ago 290
reST (reStructuredText) Question

Spring data jpa - Return map

I have a database with various values, all associated with a date. What I wanna do is to return a map with the date and the average of all values associated with the date. Everytime I make a request I get the following response:

"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"

My code:

@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);

Answer Source

What you have above is a json object. There must be code that calls the findDailyAverages method and converts it to Json object. If you dont want to change the then parse the JSONObject (your response above) and create 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);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download