zoukankan      html  css  js  c++  java
  • Mybatis-Plus查询返回Map类型数据

    Mybatis-Plus查询返回Map类型数据

    我们前面的案例都是返回的集合List<T>;

    集合List的弊端是会把所有的列属性都封装返回,但是我们有时候,只需要返回几个字段,然后再返回到用户端;

    所以mp框架给我们提供了List<Map<String, Object>>返回类型,String是列名,Object是值,只返回select的字段;

    举例:

    /**
     * 查询每个部门的平均薪资
     * sql: SELECT departmentId,AVG(salary) AS avg_salary FROM t_employee GROUP BY department_id;
     */
    @Test
    public void selectByQueryWrapper9(){
        QueryWrapper<Employee> queryWrapper=new QueryWrapper();
        // QueryWrapper<Employee> queryWrapper2=Wrappers.<Employee>query();
        queryWrapper
                 .select("department_id","AVG(salary) AS avg_salary")
                 .groupBy("department_id");
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
        System.out.println(employeeList);
    }

    返回值:

    [Employee(id=null, name=null, birthday=null, gender=null, email=null, phoneNumber=null, salary=null, department_id=1, avg_salary=3000.0000), Employee(id=null, name=null, birthday=null, gender=null, email=null, phoneNumber=null, salary=null, department_id=2, avg_salary=3765.0000), Employee(id=null, name=null, birthday=null, gender=null, email=null, phoneNumber=null, salary=null, department_id=3, avg_salary=4000.0000), Employee(id=null, name=null, birthday=null, gender=null, email=null, phoneNumber=null, salary=null, department_id=4, avg_salary=5000.0000)]

    没用的字段也返回了;

    我们改用Map

    /**
     * 查询每个部门的平均薪资(返回Map)
     * sql: SELECT departmentId,AVG(salary) AS avg_salary FROM t_employee GROUP BY department_id;
     */
    @Test
    public void selectByQueryWrapper10ReturnMap(){
        QueryWrapper<Employee> queryWrapper=new QueryWrapper();
        // QueryWrapper<Employee> queryWrapper2=Wrappers.<Employee>query();
        queryWrapper
                 .select("department_id","AVG(salary) AS avg_salary")
                 .groupBy("department_id");
        List<Map<String, Object>> maps = employeeMapper.selectMaps(queryWrapper);
        System.out.println(maps);
    }

    返回结果:

    [{department_id=1, avg_salary=3000.0000}, {department_id=2, avg_salary=3765.0000}, {department_id=3, avg_salary=4000.0000}, {department_id=4, avg_salary=5000.0000}]

     

    这样的结果才比较友好;

     

    ------------------------------------------------------------------------------------------------------------------------------

    作者: java1234_小锋

    出处:https://www.cnblogs.com/java688/p/13672029.html

    版权:本站使用「CC BY 4.0」创作共享协议,转载请在文章明显位置注明作者及出处。

    ------------------------------------------------------------------------------------------------------------------------------

  • 相关阅读:
    反馈表单,JQUERY无刷新,数字验证
    漂亮的js删除确认提示框
    AJAX jQuery tab,动态加载选显卡
    获取系统变量的小小程序
    synchronized的用法简介
    代理模式之浅谈
    java生成可执行文件的方法总结
    设计模式之策略模式浅谈
    Android通过Socket(TCP/IP)与PC通讯
    JavaGUI编程简单介绍
  • 原文地址:https://www.cnblogs.com/java688/p/13672029.html
Copyright © 2011-2022 走看看