Wrapper usage example of MyBatisPlus

1. Introduction to wapper

Source code: https://gitee.com/charlinchenlin/store-pos

1, the Wrapper family

In MP, we can use general-purpose Mapper (BaseMapper) to implement basic queries, or use custom Mapper (custom XML) to implement more advanced queries. Of course, you can also combine the condition constructor to implement more advanced queries conveniently.
insert image description here

Wrapper : 条件构造抽象类,最顶端父类  
    AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件
        QueryWrapper : 查询条件封装
        UpdateWrapper : Update 条件封装
    AbstractLambdaWrapper : 使用Lambda 语法
        LambdaQueryWrapper :用于Lambda语法使用的查询Wrapper
        LambdaUpdateWrapper : Lambda 更新封装Wrapper

2. Create a test user table and entity class

CREATE TABLE `user`  (
  `id` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
  `username` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户名',
  `password` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密码',
  `address` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '地址',
  `email` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '电子邮件',
  `age` int(3) NULL DEFAULT NULL COMMENT '年龄',
  `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `modify_time` datetime(0) NULL DEFAULT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
@Data
public class User {
    
    
    
    private String id;
    
    private String username;
    
    private String password;
    
    private String address;
    
    private Integer age;
    
    private Date craeteTime;
    
    private Date modifyTime;
}

3. Create a test class

@SpringBootTest
public class WrapperTests {
    
    
    
    @Resource
    private UserMapper userMapper;
}

4. QueryWrapper test example

1. Assembly query conditions

Query users whose name contains n, whose age is greater than or equal to 10 and less than or equal to 20, and whose email address is not empty

@Test
public void test1() {
    
    

    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper
        .like("name","n")
        .between("age", 10, 20)
        .isNotNull("email");
    List<User> users = userMapper.selectList(queryWrapper);
    users.forEach(System.out::println);
}

2. Assembly sorting conditions

Query users in descending order of age, if they are the same age, sort them in ascending order by id

@Test
public void test2() {
    
    

    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper
        .orderByDesc("age")
        .orderByAsc("id");

    List<User> users = userMapper.selectList(queryWrapper);
    users.forEach(System.out::println);
}

3. Assembly and deletion conditions

Delete users with empty email

@Test
public void test3() {
    
    

    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.isNull("email");
    int result = userMapper.delete(queryWrapper); //条件构造器也可以构建删除语句的条件
    System.out.println("delete return count = " + result);
}

4. Priority of conditions

Query names containing n, and (users whose age is less than 18 or whose email address is empty), and set the age of these users to 18, and their email address to [email protected]

@Test
public void test4() {
    
    

    //修改条件
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper
        .like("name", "n")
        .and(i -> i.lt("age", 18).or().isNull("email")); //lambda表达式内的逻辑优先运算

    User user = new User();
    user.setAge(18);
    user.setEmail("[email protected]");
    int result = userMapper.update(user, queryWrapper);
    System.out.println(result);
}

5. Implement subqueries

Query the id list of all users whose id is not greater than 3

@Test
public void test6() {
    
    

    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.inSql("id", "select id from user where id <= 3");

    //selectObjs的使用场景:只返回一列
    List<Object> objects = userMapper.selectObjs(queryWrapper);//返回值是Object列表
    objects.forEach(System.out::println);
}

Note: But the above method is easy to cause sql injection

queryWrapper.inSql("id", "select id from user where id <= 3 or true"); // 或插叙出所有用户id

But use the following query to replace

queryWrapper.in("id", 1, 2, 3 );
// 或
queryWrapper.le("id", 3 );

Five, UpdateWrapper test example

Query names containing n, and (users whose age is less than 18 or whose email address is empty), and set the age of these users to 18, and their email address to [email protected]

@Test
public void test7() {
    
    
    
    //组装set子句
    UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
    updateWrapper
        .set("age", 18)
        .set("email", "[email protected]")
        .like("name", "n")
        .and(i -> i.lt("age", 18).or().isNull("email")); //lambda表达式内的逻辑优先运算

    //这里必须要创建User对象,否则无法应用自动填充。如果没有自动填充,可以设置为null
    User user = new User();
    int result = userMapper.update(user, updateWrapper);
    System.out.println(result);
}

6. Use condition to dynamically assemble query conditions

Query users whose name contains n and whose age is greater than 10 and less than 20. The query condition comes from user input and is optional

@Test
public void test8() {
    
    
    
    //定义查询条件,有可能为null(用户未输入)
    String name = null;
    Integer ageBegin = 10;
    Integer ageEnd = 20;

    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    if(StringUtils.isNotBlank(name)){
    
    
        queryWrapper.like("name","n");
    }
    if(ageBegin != null){
    
    
        queryWrapper.ge("age", ageBegin);
    }
    if(ageEnd != null){
    
    
        queryWrapper.le("age", ageEnd);
    }

    List<User> users = userMapper.selectList(queryWrapper);
    users.forEach(System.out::println);
}

There is no problem with the above implementation scheme, but the code is more complicated. We can use the overloaded method with the condition parameter to construct the query condition and simplify the code writing

@Test
public void test8Condition() {
    
    

    //定义查询条件,有可能为null(用户未输入)
    String name = null;
    Integer ageBegin = 10;
    Integer ageEnd = 20;

    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper
        .like(StringUtils.isNotBlank(name), "name", "n")
        .ge(ageBegin != null, "age", ageBegin)
        .le(ageEnd != null, "age", ageEnd);

    List<User> users = userMapper.selectList(queryWrapper);
    users.forEach(System.out::println);
}

Seven, LambdaXxxWrapper test example

1. Query users whose age is between 10 and 20

@Test
public void test9() {
    
    

    //定义查询条件,有可能为null(用户未输入)
    String name = null;
    Integer ageBegin = 10;
    Integer ageEnd = 20;

    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper
        //避免使用字符串表示字段,防止运行时错误
        .like(StringUtils.isNotBlank(name), User::getName, "n")
        .ge(ageBegin != null, User::getAge, ageBegin)
        .le(ageEnd != null, User::getAge, ageEnd);

    List<User> users = userMapper.selectList(queryWrapper);
    users.forEach(System.out::println);
}

2. Update the user email whose email is empty

@Test
public void test10() {
    
    

    //组装set子句
    LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
    updateWrapper
        .set(User::getAge, 18)
        .set(User::getEmail, "[email protected]")
        .like(User::getName, "n")
        .and(i -> i.lt(User::getAge, 18).or().isNull(User::getEmail)); //lambda表达式内的逻辑优先运算
    
 	User user = new User();
    int result = userMapper.update(user, updateWrapper);
    System.out.println(result);
}

Guess you like

Origin blog.csdn.net/lovoo/article/details/129740271