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」創作共享協議,轉載請在文章明顯位置注明作者及出處。

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM