TrueOctopus
2023-03-16

MP条件构造器

条件构造器

具体见官网文档:

条件构造器

以下是常用的基本操作:

  • allEq
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public void testAllEq(){  

Map<String,Object> params = new HashMap<>();
params.put("name", "李四");
params.put("age", "20");
params.put("password", null);

QueryWrapper<User> wrapper = new QueryWrapper<>();
//SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE password IS NULL AND name = ? AND age = ?
//wrapper.allEq(params);

//SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE name = ? AND age = ?
//wrapper.allEq(params, false);

//SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE age = ?
//wrapper.allEq((k, v) -> (k.equals("age") || k.equals("id")) , params);

//SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE name = ? AND age = ?
wrapper.allEq((k, v) -> (k.equals("age") || k.equals("id") || k.equals("name")) , params);

List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
  • like %值%

  • notLike %值% 取反

  • likeLeft %值

  • likeRight 值%

1
2
3
4
5
6
7
8
9
10
11
public void testLike(){  
QueryWrapper<User> wrapper = new QueryWrapper<>();
// SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE name LIKE ?
// 参数:%五(String)
wrapper.likeLeft("name", "五");

List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
  • or
1
2
3
4
5
6
7
8
9
10
public void testOr(){  
QueryWrapper<User> wrapper = new QueryWrapper<>();
// SELECT id,user_name,name,age,email AS mail FROM tb_user WHERE name = ? OR age = ?
wrapper.eq("name", "王五").or().eq("age", 21);

List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}
  • select部分
1
2
3
4
5
6
7
8
9
10
11
12
13
public void testSelect(){  
QueryWrapper<User> wrapper = new QueryWrapper<>();
//SELECT id,name,age FROM tb_user WHERE name = ? OR age = ?
wrapper.eq("name", "王五")
.or()
.eq("age", 21)
.select("id","name","age"); //指定查询的字段

List<User> users = this.userMapper.selectList(wrapper);
for (User user : users) {
System.out.println(user);
}
}