条件构造器select方法介绍
根据业务需求,有时候只需要返回特定的几个数据表字段,我们通过条件构造器的select方法可以指定;
还有一种情况,假如数据库字段很多的时候,我们要排除某几个字段,其他字段返回的时候,select方法也支持排除某些字段,查询其他的;
最后还有一种情况,我们搞分组聚合函数的时候,可以使用select方法,返回聚合函数执行后的数据字段;
实例一:查找薪水大于3500 名字里有“小”的 员工 (只显示编号和姓名)
@Test public void selectByQueryWrapper7(){ QueryWrapper<Employee> queryWrapper=new QueryWrapper(); // QueryWrapper<Employee> queryWrapper2=Wrappers.<Employee>query(); queryWrapper.select("id","name").gt("salary",3500).like("name","小"); List<Employee> employeeList = employeeMapper.selectList(queryWrapper); System.out.println(employeeList); }
实例二:查找薪水大于3500 名字里有“小”的 员工 (排除出生日期和性别)
@Test public void selectByQueryWrapper8(){ QueryWrapper<Employee> queryWrapper=new QueryWrapper(); // QueryWrapper<Employee> queryWrapper2=Wrappers.<Employee>query(); queryWrapper .select(Employee.class,fieldInfo->!fieldInfo.getColumn().equals("birthday")&&!fieldInfo.getColumn().equals("gender")) .gt("salary",3500) .like("name","小"); List<Employee> employeeList = employeeMapper.selectList(queryWrapper); System.out.println(employeeList); }
实例三:查询每个部门的平均薪资
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); }