Mybatis-Plus——sum聚合函数 及 按日期查询并求和

一.Mybatis-Plus——sum聚合函数

 //总收益
 		Order order =new Order();
        QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>();
        queryWrapper.select("sum(price) as sumAll");     
        Order ord= orderService.getOne(queryWrapper);
        //注意,空指针问题
         if (ord== null){
            order.setSumAll(Double.valueOf(0)) ;
        }else{
			 order.setSumAll(ord.getSumAll());
        }
       

对应的sql语句是

SELECT sum(price) as sumAll FROM t_order

注意:as后面的变量要与实体类中声明的一致, @TableField(exist = false)表示表中并没有相应的字段与之对应。
(queryWrapper的getOne()方法:根据 Wrapper,查询一条记录)

	/**
     * 总收益
     */
    @TableField(exist = false)
    private Double sumAll;

参考:https://blog.csdn.net/weixin_45616483/article/details/105540393?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.compare

二.按日期查询并求和(mybatis及mybatisPlus两种方式)

举例: 今日总收益

1.mybatisPlus,只需在controller层进行代码书写

//今日总收益
   QueryWrapper<Order> queryWrapper = new QueryWrapper<Order>();
   queryWrapper.select("sum(price) as sumByToday ");
   queryWrapper.eq("TO_DAYS(create_time)","TO_DAYS(NOW())");
   
   Order order =new Order();

   if (orderService.getOne(queryWrapper) == null){
            order.setSumByToday(Double.valueOf(0)) ;
   }else{
            order.setSumByToday(orderService.getOne(queryWrapper).getSumByToday());
   }

2.mybatis (自己定义sql,简单灵活,但代码量相较于mybatisPlus多了几行)

controller层

  //今日总收益
        Double sumByToday =orderService.sumByToday();
        if (sumByToday == null){
            sumByToday = Double.valueOf(0);
        }
        order.setSumByToday(sumByToday);

service层

	Double sumByToday();

service实现层

 @Override
    public Double sumByToday(){
        return orderMapper.sumByToday();
    }

mapper层

 Double sumByToday();

xml文件

 <select id="sumByToday"  resultType="java.lang.Double">
    select sum(price) as sumByToday  from t_order
     where TO_DAYS(create_time) = TO_DAYS(NOW())
    </select>

3.bug记录,错误信息如下:

Mapper method 'mapper.OrderMapper.sumByToday attempted to return null from a method with a primitive return type (double).
查询出来的值为空,它的数据为null而不是double数据。

解决方法:
方法1:实体类中用来接收“今日总收益“的变量,类型变成封装类Double(Integer、Long,而不是double。
方法2:xml文件中的sql语句变成

select IFNULL(sum(price),0) as sumByToday 
from t_order
where TO_DAYS(create_time) = TO_DAYS(NOW())

IFNULL(expression, value):如果第一个参数的表达式 expression 为 NULL,则返回第二个参数的备用值。

你可能感兴趣的:(mybatis-plus,java,mybatis)