使用 Wrapper 查询
# ge gt le lt isNull isNotNull
@Test
public void testWrapperQuery1(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
.ge("age",22)
.isNotNull("email");
List<User> users = userMapper.selectList(queryWrapper);
System.out.println(users);
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
- 同理支持 gt le lt isNull
# eq ne
@Test
public void testWrapperQuery2(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("email","work_stt@163.com");
User user = userMapper.selectOne(queryWrapper);
System.out.println(user);
}
1
2
3
4
5
6
7
2
3
4
5
6
7
- 注意:selectOne只查询一条记录,如果数据库中匹配到多条记录则会报错
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 2
1
# between notBetween
- 注意:包含大小边界
@Test
public void testWrapperQuery3() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.between("age", 18, 20);
Integer count = userMapper.selectCount(queryWrapper);
System.out.println(count);
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# like notLike likeLeft likeRight
- selectMaps() 返回的Map集合列表,通常配合select()使用
@Test
public void testWrapperQuery4() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
.select("name", "age")
.like("name", "st") // like '%st%'
.likeRight("email", "work_"); // like 'work_%'
List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
maps.forEach(System.out::println);
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# orderBy orderByDesc orderByAsc
@Test
public void testWrapperQuery5(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.orderByDesc("age","id");
List<User> users = userMapper.selectList(queryWrapper);
System.out.println(users);
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 支持的查询方式
查询方式 | 说明 |
---|---|
setSqlSelect | 设置 SELECT 查询字段 |
where | WHERE 语句,拼接 + WHERE 条件 |
and | AND 语句,拼接 + AND 字段=值 |
andNew | AND 语句,拼接 + AND (字段=值) |
or | OR 语句,拼接 + OR 字段=值 |
orNew | OR 语句,拼接 + OR (字段=值) |
eq | 等于= |
allEq | 基于 map 内容等于= |
ne | 不等于<> |
gt | 大于> |
ge | 大于等于>= |
lt | 小于< |
le | 小于等于<= |
like | 模糊查询 LIKE |
notLike | 模糊查询 NOT LIKE |
in | IN 查询 |
notIn | NOT IN 查询 |
isNull | NULL 值查询 |
isNotNull | IS NOT NULL |
groupBy | 分组 GROUP BY |
having | HAVING 关键词 |
orderBy | 排序 ORDER BY |
orderAsc | ASC 排序 ORDER BY |
orderDesc | DESC 排序 ORDER BY |
exists | EXISTS 条件语句 |
notExists | NOT EXISTS 条件语句 |
between | BETWEEN 条件语句 |
notBetween | NOT BETWEEN 条件语句 |
addFilter | 自由拼接 SQL |
last | 拼接在最后,例如:last(“LIMIT 1”) |
Last Updated: 2022/01/16, 11:29:51