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

待我称王封你为后i 2021-07-16 15:17 1276阅读 0赞

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

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

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

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

举例:

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

返回值:

[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`

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

返回结果:

[{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}]

这样的结果才比较友好;

发表评论

表情:
评论列表 (有 0 条评论,1276人围观)

还没有评论,来说两句吧...

相关阅读