[英]Spring JPA Custom Query to return JSON
I am using Spring hibernate with JPA Repository to return the values as JSON. 我正在将Spring hibernate与JPA Repository结合使用以将值返回为JSON。 It works fine for all default cases.
它适用于所有默认情况。 I am having a problem with custom query in my CrudRepository to return aggregated values as JSON.
我在CrudRepository中的自定义查询有问题,无法将汇总值作为JSON返回。
CrudRepository Crud存储库
@Repository
public interface ExpenseRepository extends CrudRepository<Expense, Integer>{
@Query("SELECT min(dtDate) as dtDate ,Max(dtDate) as dtDate FROM Expense")
Iterable<Expense> getAvlRptDates();
}
NOTE: I have tried with and without Alias, List etc as well. 注意:我已经尝试使用或不使用别名,列表等。
Controller 控制者
@ResponseBody
@RequestMapping(value="/getAvlExpMonthYear",method=RequestMethod.GET)
public Iterable<Expense> getAvlRptDates(){
//String test = testRepo.findAll().toString();
return expRepo.getAvlRptDates();
}
I tried with List as well. 我也尝试过List。 I know that converting to JSON with custom code or additional dto classes.
我知道可以使用自定义代码或其他dto类转换为JSON。
Please let me know if there any easy way without creating additional domain class or dto classes just for two fields. 请让我知道是否有简单的方法而不必为两个字段创建其他域类或dto类。
Change this: 更改此:
@Repository
public interface ExpenseRepository extends CrudRepository<Expense, Integer>{
@Query("SELECT min(dtDate) as dtDate ,Max(dtDate) as dtDate FROM Expense")
Iterable<Expense> getAvlRptDates();
}
To the following changing Iterable to Optional which returns a list of Jsons: 对于以下内容,将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();
}
Now, you will get some sort of JSON but not the kind of json that meets official standards. 现在,您将获得某种JSON,但不会获得符合官方标准的JSON。
So my recommendation is to do: 所以我的建议是:
@Repository
public interface ExpenseRepository extends CrudRepository<Expense, Integer>{
@Query("SELECT min(dtDate) as dtDate ,Max(dtDate) as dtDate FROM Expense")
Expense[] getAvlRptDates();
}
Where it return a single iterable, then convert the contents of the iterable to json one by one. 在返回单个可迭代对象的地方,然后将可迭代对象的内容一一转换为json。 See below link:
见下面的链接:
How to convert list data into json in java 如何在Java中将列表数据转换为JSON
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.