Title

mybatis-plus查询指定字段

mybatis-plus

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

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

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

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

日志输出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()方法

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

日志输出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

 

posted @ 2020-08-13 15:43  快乐小洋人  阅读(51342)  评论(0编辑  收藏  举报