MybatisPlus入门(七)MybatisPlus-DQL编程控制
一、查询投影
查询投影:查出来的东西有多少字段,设置查询出来的结果长什么样,查出的字段控制;
查询投影适用于lamda格式,使用select 查询 lqw.select(User::getId,User::getName,User::getAge);
代码示例:
LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
lqw.select(User::getId,User::getName,User::getAge);
QueryWrapper<User> lqw = new QueryWrapper<User>();
lqw.select("id","name","age","tel");
List<User> userList = userDao.selectList(lqw);
System.out.println(userList);
普通查询查询投影,代码示例:
QueryWrapper<User> lqw = new QueryWrapper<User>();
lqw.select("id", "name", "age", "tel");
List<User> userList = userDao.selectList(lqw);
System.out.println(userList);
查询 count (*)使用List<Map<String, Object>> userList = userDao.selectMaps(lqw);
查询投影和分组代码示例:
QueryWrapper<User> lqw = new QueryWrapper<User>();
lqw.select("count(*) as count, tel");
lqw.groupBy("tel");
List<Map<String, Object>> userList = userDao.selectMaps(lqw);
System.out.println(userList);
查询结果包含模型类中部分属性,代码示例:
/*LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
lqw.select(User::getId, User::getName, User::getAge);*/
//或者
QueryWrapper<User> lqw = new QueryWrapper<User>();
lqw.select("id", "name", "age", "tel");
List<User> userList = userDao.selectList(lqw);
System.out.println(userList);
查询结果包含模型类中未定义的属性,代码示例:
QueryWrapper<User> lqw = new QueryWrapper<User>();
lqw.select("count(*) as count, tel");
lqw.groupBy("tel");
List<Map<String, Object>> userList = userDao.selectMaps(lqw);
System.out.println(userList);
二、查询条件设置
查询条件如下图:
用户登录(eq匹配),代码示例:
LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
//等同于=
lqw.eq(User::getName, "Jerry").eq(User::getPassword, "jerry");
User loginUser = userDao.selectOne(lqw);
System.out.println(loginUser);
购物设定价格区间、户籍设定年龄区间(le ge匹配 或 between匹配)
代码示例:
LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
//范围查询 lt le gt ge eq between
//范围查询 lt le (不带等号 ) gt ge(带等号) eq between
lqw.between(User::getAge, 10, 30);
List<User> userList = userDao.selectList(lqw);
System.out.println(userList);
注意:范围查询 lt le (不带等号 ) gt ge(带等号) eq between
模糊匹配 ,查信息,搜索新闻(非全文检索版:like匹配)代码示例:
LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>();
//模糊匹配 like likeRight likeLeft
lqw.likeLeft(User::getName, "J");
List<User> userList = userDao.selectList(lqw);
System.out.println(userList);
统计报表(分组查询聚合函数),代码示例:
QueryWrapper<User> qw = new QueryWrapper<User>();
qw.select("gender","count(*) as nums");
qw.groupBy("gender");
List<Map<String, Object>> maps = userDao.selectMaps(qw);
System.out.println(maps);