MyBatis-Plus整合SpringBoot及使用

MyBatis-Plus是一个为简化开发而生的MyBatis增强工具,在Java开发领域广受欢迎。它继承了MyBatis的所有特性,并且通过引入强大的功能增强,极大减少了开发者的工作量。对于使用Spring Boot开发的项目,整合MyBatis-Plus能够使数据访问层的代码更加简洁,增强开发效率。在本文中,我们将详细探讨如何在Spring Boot项目中整合MyBatis-Plus并简要介绍其使用。

Spring Boot项目中整合MyBatis-Plus的步骤

  1. 依赖配置

    在项目的 pom.xml文件中引入Spring Boot的依赖和MyBatis-Plus的依赖。确保你的Spring Boot版本与MyBatis-Plus版本兼容。

    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.3.1.RELEASE
    
    
    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
    
    
        com.baomidou
        mybatis-plus-boot-starter
        3.4.0
    
    
  2. 配置数据源

    在 application.properties或 application.yml文件中配置数据库连接、Mybatis-Plus的扫描路径等信息。

    spring:
        datasource:
            driver-class-name: com.mysql.cj.jdbc.Driver
            url: jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT
            username: root
            password: password
    mybatis-plus:
        mapper-locations: classpath:/mapper/*.xml
        type-aliases-package: com.yourcompany.project.model
        global-config:
            banner: false
    
  3. 编写Entity和Mapper

    在项目中创建对应的实体类和Mapper接口。MyBatis-Plus能够通过简单的注解和继承基类 BaseMapper来减少大量的样板代码。

    // Entity类示例
    @Data
    @TableName("user")
    public class User {
        @TableId(type = IdType.AUTO)
        private Long id;
        private String name;
        private Integer age;
        private String email;
    }
    
    // Mapper接口示例
    @Repository
    public interface UserMapper extends BaseMapper {
        // 此处可以添加自定义的数据库操作方法
    }
    
  4. 启动类注解

    在Spring Boot的启动类中添加 @MapperScan注解,指示Spring Boot扫描Mapper接口。

    @SpringBootApplication
    @MapperScan("com.yourcompany.project.mapper")
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    

基本使用

整合完成后,你可以开始享受MyBatis-Plus带来的便利性。通过继承 BaseMapper,你的Mapper接口自动拥有了CRUD的能力,大多数的数据访问操作不再需要手写SQL。对于复杂的查询,MyBatis-Plus提供了强大灵活的查询构造器 QueryWrapper和 UpdateWrapper,让动态SQL的构建变得简单。

// 使用MyBatis-Plus的BaseMapper进行简单CRUD操作
@Autowired
private UserMapper userMapper;

public void testMyBatisPlus() {
   // 新增用户
   User user = new User();
   user.setName("John Doe");
   user.setAge(30);
   user.setEmail("[email protected]");
   userMapper.insert(user);

   // 查询用户
   User userDb = userMapper.selectById(user.getId());
   System.out.println(userDb);

   // 更新用户
   userDb.setAge(31);
   userMapper.updateById(userDb);

   // 删除用户
   userMapper.deleteById(userDb.getId());
}

你可能感兴趣的:(mybatis,spring,boot,后端)