[Study]MyBatisPlus

Posted Spring-_-Bear

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Study]MyBatisPlus相关的知识,希望对你有一定的参考价值。

一、入门案例

  1. 创建数据库与表

    CREATE DATABASE mybatis_plus;
    
    USE mybatis_plus;
    
    CREATE TABLE `user`  (
      `id` bigint NOT NULL AUTO_INCREMENT,
      `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
      `age` int NULL DEFAULT NULL,
      `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
    
    -- ----------------------------
    -- Records of user
    -- ----------------------------
    INSERT INTO `user` VALUES (1, '111', 111, '111@111.com');
    INSERT INTO `user` VALUES (2, '222', 222, '222@222.com');
    INSERT INTO `user` VALUES (3, '333', 333, '333@333.com');
    INSERT INTO `user` VALUES (4, '444', 444, '444@444.com');
    INSERT INTO `user` VALUES (5, '555', 555, '555@555.com');
    
  2. 创建 SpringBoot 工程,pom.xml 中引入依赖

    <!-- 引入 mysql connector、MyBatisPlus 依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.1</version>
    </dependency>
    
  3. 在 SpringBoot 工程的核心配置文件 application.yaml 中配置数据源信息

    spring:
      datasource:
        # 配置数据源类型
        type: com.zaxxer.hikari.HikariDataSource
        url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
        driver-class-name: com.mysql.cj.jdbc.Driver
        username: admin
        password: admin
    
  4. 创建数据库表对应的实体类 User

    /**
     * 类名需要与数据库表名一致
     *
     * @author Spring-_-Bear
     * @datetime 2022-06-15 17:34
     */
    @Data
    public class User 
        private Long id;
        private String name;
        private Integer age;
        private String email;
    
    
  5. 创建 Mapper 接口 UserMapper

    /**
     * UserMapper.java
     * @author Spring-_-Bear
     * @datetime 2022-06-15 17:35
     */
    public interface UserMapper extends BaseMapper<User> 
    
    
  6. 创建 Service 接口及其实现类

    /**
     * UserService.java
     *
     * @author Spring-_-Bear
     * @datetime 2022-06-16 07:29
     */
    @Service
    public interface UserService extends IService<User> 
    
    
    /**
     * UserServiceImpl.java
     * 
     * @author Spring-_-Bear
     * @datetime 2022-06-16 07:29
     */
    @Service
    public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService 
    
    
  7. 在 SpringBoot 的配置类中开启接口所在包扫描

    @MapperScan("edu.whut.bear.mybatisplus.mapper")
    @SpringBootApplication
    public class MainApplication 
        public static void main(String[] args) 
            SpringApplication.run(MainApplication.class, args);
        
    
    
  8. application.yaml中加入日志功能

    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
  9. 测试一把

    @SpringBootTest
    class MainApplicationTests 
        @Autowired
        private UserMapper userMapper;
    
        @Test
        public void getAllUsers() 
            List<User> users = userMapper.selectList(null);
            users.forEach(System.out::println);
        
    
    

二、简单 CRUD

  1. 新增记录并返回自增主键

    @Test
    public void insert() 
        User user = new User(null, "bear", 11, "bear@bear.com");
        int res = userMapper.insert(user);
        // User(id=1537210730757947393, name=bear, age=11, email=bear@bear.com)
        System.out.println(user);
    
    
  2. 通过指定条件删除记录、批量删除记录

    @Test
    public void deleteByMap() 
        Map<String, Object> map = new HashMap<>();
        map.put("name", "bear");
        map.put("age", 13);
        // DELETE FROM user WHERE name = ? AND age = ?
        System.out.println(userMapper.deleteByMap(map));
    
    
    @Test
    public void deleteBatchIds() 
        List<Integer> list = Arrays.asList(1, 2, 3);
        // DELETE FROM user WHERE id IN ( ? , ? , ? )
        System.out.println(userMapper.deleteBatchIds(list));
    
    
  3. 通过实体类对象中的非空属性修改数据

    @Test
    public void updateById() 
        User user = new User(4L, "springbear", 22, "2020@163.com");
        // UPDATE user SET name=?, age=?, email=? WHERE id=?
        System.out.println(userMapper.updateById(user));
    
    
  4. 不指定条件查询所有用户记录

    @Test
    public void getAllUsers()
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);
    
    

三、常用注解

  1. @TableName 设置当前实体类对应的数据库表名

    /**
     * @author Spring-_-Bear
     * @datetime 2022-06-15 17:34
     */
    @Data
    @TableName("t_user")
    public class User ...
    
  2. @TableId 将当前实体类的字段指定映射到数据库表的主键字段,value 属性指明数据库表主键名称,type 属性知名数据库表 id 自增类型

    public class User 
        /**
         * 将当前字段指定映射为数据库表的主键
         * 指定数据库表字段名,设置 ID 生成策略为自增 AUTO_INCREMENT
         */
        @TableId(value = "uid", type = IdType.AUTO)
        private Long id;
    
    
  3. @TableField 设置当前实体类对应的数据库表字段

    public class User
        /**
         * 设置 POJO 属性对应数据库表的字段名
         */
        @TableField("username")
        private String name;
    
    
  4. @TableLogic 设置当前字段逻辑删除字段,删除时逻辑删除对应的记录而非物理删除,查询时也总会带上记录存在的逻辑条件 ... WHERE isDELETED = 0 AND ...

    public class User
        /**
         * 设置为逻辑字段,当执行表记录删除操作时修改对应的 is_deleted 状态(默认为 0,修改后为 1)
         * 查询时总是查询 SELECT ... FROM ... WHERE id_deleted = 0,MyBatisPlus 中默认开启了自动驼峰命名转换
         */
        @TableLogic
        private Integer isDeleted;
    
    

四、Wrapper

4.1 继承体系图

4.2 QueryWrapper

  1. SELECT

    @Test
    public void selectWrapper() 
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 查询 name 字段含有 bear 且年龄在 10-20 之间的记录
        queryWrapper.like("name", "bear").between("age", 10, 20);
        // SELECT id,name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND (name LIKE ? AND age BETWEEN ? AND ?)
        List<User> userList = userMapper.selectList(queryWrapper);
        userList.forEach(System.out::println);
    
    
  2. ORDER BY

    @Test
    public void orderWrapper() 
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 先按 age 降序排,再按 id 升序排
        queryWrapper.orderByDesc("age").orderByAsc("id");
        // SELECT id,name,age,email,is_deleted FROM t_user WHERE is_deleted=0 ORDER BY age DESC,id ASC
        List<User> users = userMapper.selectList(queryWrapper);
        users.forEach(System.out::println);
    
    
  3. DELETE

    @Test
    public void deleteWrapper() 
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 删除 email 为空的记录
        queryWrapper.isNull("email");
        // DELETE FROM t_user WHERE (email IS NULL)
        int res = userMapper.delete(queryWrapper);
        System.out.println(res);
    
    
  4. UPDATE

    @Test
    public void deleteWrapper() 
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 将【年龄大于 20 且名字中含有字母 a】或【邮箱为空】的用户信息进行修改
        queryWrapper.gt("age", 20).like("name", "a")
            .or().isNull("email");
        User user = new User(null, "springbear", 22, "springbear2020@163.com");
        // UPDATE t_user SET name=?, age=?, email=? WHERE (age > ? AND name LIKE ? OR email IS NULL)
        int res = userMapper.update(user, queryWrapper);
        System.out.println(res);
    
    
  5. 控制条件优先级

    @Test
    public void priorityWrapper() 
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 将【名字中含有字母 a】并且【年龄大于 20 或邮箱为空的用户信息进行修改】,在 MyBatisPlus 中 Lambda 表达式中的条件会优先执行
        //  
        queryWrapper.like("name", "a")
            .and(i -> i.gt("age", 20).or().isNull("email"));
        User user = new User(null, "bear", 22, "bear@bear.com");
        // UPDATE t_user SET name=?, age=?, email=? WHERE (name LIKE ? AND (age > ? OR email IS NULL))
        int res = userMapper.update(user, queryWrapper);
        System.out.println(res);
    
    
  6. 查询特定的列

    @Test
    public void columnWrapper() 
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 查询特定列
        queryWrapper.select("name", "age");
        // SELECT name,age FROM t_user
        List<Map<String, Object>> userMaps = userMapper.selectMaps(queryWrapper);
        userMaps.forEach(System.out::println);
    
    
  7. 子查询

    @Test
    public void subQueryWrapper() 
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 子查询
        queryWrapper.inSql("id", "select id from t_user where id < 100");
        // SELECT id,name,age,email FROM t_user WHERE (id IN (select id from t_user where id < 100))
        List<User> users = userMapper.selectList(queryWrapper);
        users.forEach(System.out::println);
    
    
  8. 条件组装查询(当满足指定的条件时才组装该条件)

    @Test
    public void conditionWrapper() 
        String username = "springbear";
        int maxAge = 1000;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 条件组装查询:username 中含有 "bear",最大年龄小于 100
        queryWrapper.like(username.contains("bear"), "name", username)
            .lt(maxAge < 100, "age", maxAge);
        // SELECT id,name,age,email FROM t_user WHERE (name LIKE ?)
        List<User> users = userMapper.selectList(queryWrapper);
        users.forEach(System.out::println);
    
    

4.3 UpdateWrapper

@Test
public void updateWrapper() 
    UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
    // 将【名字中含有字母 a】并且【年龄大于 20 或邮箱为空的用户信息进行修改】,在 MyBatisPlus 中 Lambda 表达式中的条件会优先执行
    updateWrapper.like("name", "a")
        .and(i -> i.gt("age", 20).or().isNull("email"));
    // 设置要修改的字段
    updateWrapper.set("name", "熊猫");
    // UPDATE t_user SET name=? WHERE (name LIKE ? AND (age > ? OR email IS NULL))
    int res = userMapper.update(null, updateWrapper);
    System.out.println(res);

4.4 AbstractLambdaWrapper

@Test
public void lambdaQueryWrapper() 
    String name = "bear";
    int maxAge = 100;
    LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    // 使用 Lambda 函数式接口自动获取 POJO 字段对应的数据库表字段名(LambdaQueryWrapper 使用方法一致)
    lambdaQueryWrapper.like(name != null, User::getName, name)
        .ge(maxAge <= 100, User::getAge, maxAge);
    //  SELECT id,name,age,email FROM t_user WHERE (name LIKE ? AND age >= ?)
    List<User> users = userMapper.selectList(lambdaQueryWrapper);
    users.forEach(System.out::println);

五、高级功能

5.1 分页插件

  1. 在任意的配置类中配置分页组件 PaginationInnerInterceptor

    /**
     * 创建配置类配置 MyBatisPlus 分页组件
     *
     * @author Spring-_-Bear
     * @datetime 2022-06-16 16:59
     */
    @Configuration
    // 扫描 InterfaceMapper 所在包
    @MapperScan("edu.whut.bear.mybatisplus.mapper")
    public class MyBatisPlusConfig 
        @Bean
        public MybatisPlusInterceptor mybatisPlusInterceptor() 
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            // 设置数据库的类型
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
            return interceptor;
        
    
    
  2. 测试一把

    @Test
    public void page() 
        int currentPage = 1<

    以上是关于[Study]MyBatisPlus的主要内容,如果未能解决你的问题,请参考以下文章

    python 内包表记

    python リスト内包表记

    html ¥·税込·税抜表记

    html ¥·税込·税抜表记

    html ¥·税込·税抜表记

    python 快译通のリスト内包表记