Mybatis-Plus条件构造器的select

select作用:选取指定的数据库字段,避免查询冗余的字段。

下面简单叙述一下select的用法;

1、查询除了指定字段以外的所有字段

方法:QueryWrapper select(Class entityClass, Predicate predicate)

    @GetMapping(value = "/test")
    public List test(Animal arg) {
        QueryWrapper wrapper = Wrappers.query(arg)
                .select(Animal.class, item -> ! item.getColumn().equals("age"));
        return animalService.list(wrapper);
    }

控制台打印的sql语句如下:

SELECT
	id,
	create_time,
	NAME,
	update_time,
	del_flag,
	hobby 
FROM
	animal 
WHERE
	del_flag =0

2、查询指定字段

方法:QueryWrapper select(String... columns)

    @GetMapping(value = "/test")
    public List test(Animal arg) {
        QueryWrapper wrapper = Wrappers.query(arg)
                .select("id", "name", "hobby");
        return animalService.list(wrapper);
    }

控制台打印的sql语句如下:

SELECT id,name,hobby FROM animal WHERE del_flag=0

3、结合聚合函数查询

方法:QueryWrapper select(String... columns)

查询各个部门员工的平均年龄,然后按照部门id降序排序 

    @GetMapping(value = "/test")
    public List test(Animal arg) {
        QueryWrapper wrapper = Wrappers.query(arg)
                .select("dept_id", "AVG(age) AS avgAge")
                .groupBy("dept_id")
                .orderByDesc("dept_id");
        return animalService.list(wrapper);
    }

 控制台打印的sql语句如下:

SELECT
	dept_id,
	AVG( age ) AS avgAge 
FROM
	animal 
WHERE
	del_flag = 0 
GROUP BY
	dept_id 
ORDER BY
	dept_id DESC
	

你可能感兴趣的:(笔记,sql,java)