mybatis-plus select查询语句默认是查全部字段,有两种方法可以指定要查询的字段

  1. CREATE TABLE `user` (
  2. `id` bigint(20) NOT NULL COMMENT '主键',
  3. `name` varchar(30) DEFAULT NULL COMMENT '姓名',
  4. `age` int(11) DEFAULT NULL COMMENT '年龄',
  5. `email` varchar(50) DEFAULT NULL COMMENT '邮箱',
  6. `manager_id` bigint(20) DEFAULT NULL COMMENT '直属上级id',
  7. `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  8. PRIMARY KEY (`id`),
  9. KEY `manager_fk` (`manager_id`),
  10. CONSTRAINT `manager_fk` FOREIGN KEY (`manager_id`) REFERENCES `user` (`id`)
  11. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

1、user表只需要查询出name和age两个字段的数据,可以使用queryWrapper的select()方法指定要查询的字段

  1. @Test
  2. public void selectByWrapper10() {
  3. QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  4. queryWrapper.select("name", "age").like("name", "雨");
  5. List<User> users = userMapper.selectList(queryWrapper);
  6. users.forEach(System.out::println);
  7. }

日志输出sql:

DEBUG==> Preparing: SELECT name,age FROM user WHERE name LIKE ?
DEBUG==> Parameters: %雨%(String)
TRACE<== Columns: name, age
TRACE<== Row: 张雨琪, 31
TRACE<== Row: 刘红雨, 31
DEBUG<== Total: 2

2、user表要查询出除manager_id和create_time外其它所有字段的数据,同样也是使用queryWrapper的select()方法

  1. @Test
  2. public void selectByWrapper11() {
  3. QueryWrapper<User> queryWrapper = new QueryWrapper<>();
  4. queryWrapper.select(User.class, info -> !info.getColumn().equals("manager_id")
  5. && !info.getColumn().equals("create_time"));
  6. List<User> users = userMapper.selectList(queryWrapper);
  7. users.forEach(System.out::println);
  8. }

日志输出sql:

DEBUG==> Preparing: SELECT id,name,age,email FROM user
DEBUG==> Parameters:
TRACE<== Columns: id, name, age, email
TRACE<== Row: 1087982257332887553, 大boss, 40, boss@baomidou.com
TRACE<== Row: 1088248166370832385, 王天风, 25, wtf@baomidou.com
TRACE<== Row: 1088250446457389058, 李艺伟, 28, lyw@baomidou.com
TRACE<== Row: 1094590409767661570, 张雨琪, 31, zjq@baomidou.com
TRACE<== Row: 1094592041087729666, 刘红雨, 31, lhm@baomidou.com
DEBUG<== Total: 5
https://www.jianshu.com/p/e97b8236db67