【问题标题】:How do I return 0 instead of null in postman response?如何在邮递员响应中返回 0 而不是 null?
【发布时间】:2021-03-10 01:23:09
【问题描述】:

我创建了一个 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
        }, 

【问题讨论】:

  • ispped_count 的数据类型是什么?是int 还是整数?
  • 数据类型为BigInteger
  • 在Webchallanservice类本身的构造函数中将ispped_count的值初始化为0怎么样?或者在返回if-else之前,可以加if(violation.get(location).getIspped_count()==null){violation.get(location).setIspped_count(0);}
  • 好的,先生,我试试
  • 我尝试了两种方式,但两种方式都无法初始化 0,因为它显示的 Int 值 0 不能适用于 BigInteger

标签: java mysql spring spring-boot jpa


【解决方案1】:

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

【讨论】:

  • 我需要在哪里使用合并??我根据位置 ispeed_count、rlvd_count、challan_count 获得 3 个数据,
  • 我向您展示了 ispeed_count 的查询,其余 2 个查询与上图相同??
  • 作为回应,如果该特定数据上没有数据,我将得到 null
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
相关资源
最近更新 更多