java - 如何在邮递员响应中返回 0 而不是 null?
问题描述
我制作了一个 API,它可以让我根据位置进行计数(我在此使用本机查询),这是我的服务类中的方法
public ResponseModel getData(RequestModel mRequestModel) {
JSONObject mJsonObject = new JSONObject(mRequestModel.getData());
String startDAte = mJsonObject.getString("StartDate");
// String endDate = mJsonObject.getString("EndDate");
List<ReportModel1> ispeeddetails = ispeedVio.getDataIspeed(startDAte);
List<ReportModel1> rlvdDetails = rlvdVio.getDataRlvd(startDAte);
List<ReportModel1> challanDetails = challanRepo.getChallan(startDAte);
HashMap<String,Webchallanservice> violation = new HashMap<String,Webchallanservice>();
for(ReportModel1 m:ispeeddetails) {
String location= m.getLocation();
if(violation.containsKey(location)) {
violation.get(location).setIspped_count(m.getCount());
}
else {
Webchallanservice challn = new Webchallanservice();
challn.setIspped_count(m.getCount());
violation.put(location, challn);
}
}
if (violation != null && !violation.isEmpty()) {
return Util.setResponse(AppConstant.SUCCESS_STATUS_CODE, "Successfully Fetched", violation);
} else {
return Util.setResponse(AppConstant.ERROR_STATUS_CODE, "No Record Found", violation);
}
我使用的查询是这个
@Query(value = "SELECT COUNT(*) as count ,location FROM ispeed_transits v WHERE v.entry_timestamp LIKE %:startDate% GROUP BY v.location", nativeQuery = true)
List<ReportModel1> getDataIspeed(@Param("startDate") String startDate);
我在邮递员上得到的响应是正确的,但是当没有数据时它给我 null 但我想返回 0。
"status": 1,
"message": "Successfully Fetched",
"myObjectList": {
"Taat Mill- From Jhakarkati": {
"challan_count": 3,
"ispped_count": null,
"rlvd_count": 254
},
解决方案
axtavt 非常雄辩地回答了这个问题: https ://stackoverflow.com/a/10296943/2175570
NoResultException
当没有返回行时抛出,但在您的情况下只sum
返回一行具有null
值。来自 JPA 2.0 规范:如果使用 SUM、AVG、MAX 或 MIN,并且没有可应用聚合函数的值,则聚合函数的结果为 NULL。
如果你想得到
0
而不是null
,使用coalesce
:select coalesce(sum(p.value), 0) ...
推荐阅读
- android - 将文件从节点 js 服务器下载到 android 应用程序
- regex - 我可以在 char16_t 字符串上使用 STL 正则表达式库吗?
- pandas - 重塑+分组并重命名熊猫数据框
- python - 如何制作混淆矩阵来测试python中的Conv-neural网络模型?
- python - pytest 不会在单元测试中保留类实例
- java - JUnit - 同步方法
- swift - Nested TabView - 删除内部标签栏 iOS 13,Swift UI
- macos - 在 Mac Catalina 中安装旧版本的 ilibmobiledevice ( libimobiledevice.6.dylib )
- autodesk-forge - 选定的组件在 Forge Viewer 中发光
- python - 将python 3.8中的变量分配给shell命令