首页 > 解决方案 > 如何在邮递员响应中返回 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
        }, 

标签: javamysqlspringspring-bootjpa

解决方案


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) ...

推荐阅读