[英]Spring JPA Custom Query to return JSON
我正在將Spring hibernate與JPA Repository結合使用以將值返回為JSON。 它適用於所有默認情況。 我在CrudRepository中的自定義查詢有問題,無法將匯總值作為JSON返回。
Crud存儲庫
@Repository
public interface ExpenseRepository extends CrudRepository<Expense, Integer>{
@Query("SELECT min(dtDate) as dtDate ,Max(dtDate) as dtDate FROM Expense")
Iterable<Expense> getAvlRptDates();
}
注意:我已經嘗試使用或不使用別名,列表等。
控制者
@ResponseBody
@RequestMapping(value="/getAvlExpMonthYear",method=RequestMethod.GET)
public Iterable<Expense> getAvlRptDates(){
//String test = testRepo.findAll().toString();
return expRepo.getAvlRptDates();
}
我也嘗試過List。 我知道可以使用自定義代碼或其他dto類轉換為JSON。
請讓我知道是否有簡單的方法而不必為兩個字段創建其他域類或dto類。
更改此:
@Repository
public interface ExpenseRepository extends CrudRepository<Expense, Integer>{
@Query("SELECT min(dtDate) as dtDate ,Max(dtDate) as dtDate FROM Expense")
Iterable<Expense> getAvlRptDates();
}
對於以下內容,將Iterable更改為Optional,以返回Jsons列表:
@Repository
public interface ExpenseRepository extends CrudRepository<Expense, Integer>{
@Query("SELECT min(dtDate) as dtDate ,Max(dtDate) as dtDate FROM Expense")
Optional<Expense> getAvlRptDates();
}
現在,您將獲得某種JSON,但不會獲得符合官方標准的JSON。
所以我的建議是:
@Repository
public interface ExpenseRepository extends CrudRepository<Expense, Integer>{
@Query("SELECT min(dtDate) as dtDate ,Max(dtDate) as dtDate FROM Expense")
Expense[] getAvlRptDates();
}
在返回單個可迭代對象的地方,然后將可迭代對象的內容一一轉換為json。 見下面的鏈接:
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.