Bootstrap

【SpringBoot3】Spring Boot 3.0 集成 Mybatis Plus

在Spring Boot 3.0中,你可以使用MyBatis Plus来简化数据库操作。以下是一个基本的集成示例:

1.添加依赖到你的pom.xml:

<dependencies>

    <!-- Spring Boot Starter -->

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter</artifactId>

    </dependency>

    <!-- MyBatis Plus Starter -->

    <dependency>

        <groupId>com.baomidou</groupId>

        <artifactId>mybatis-plus-boot-starter</artifactId>

        <version>3.x.x</version> <!-- 请使用最新版本 -->

    </dependency>

    <!-- 数据库驱动,以MySQL为例 -->

    <dependency>

        <groupId>mysql</groupId>

        <artifactId>mysql-connector-java</artifactId>

        <scope>runtime</scope>

    </dependency>

</dependencies>

2.配置application.properties或application.yml:

spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC

spring.datasource.username=root

spring.datasource.password=yourpassword

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

mybatis-plus.mapper-locations=classpath:/mappers/**/*.xml

mybatis-plus.type-aliases-package=com.yourpackage.model

3.创建实体类和Mapper接口:

// 实体类

@Data

public class User {

    private Long id;

    private String name;

    private Integer age;

    private String email;

}

// Mapper接口

@Mapper

public interface UserMapper extends BaseMapper<User> {

    // 这里可以添加自定义方法

}

4.在Spring Boot启动类上添加@MapperScan注解:

@SpringBootApplication

@MapperScan("com.yourpackage.mapper")

public class YourApplication {

    public static void main(String[] args) {

        SpringApplication.run(YourApplication.class, args);

    }

}

5.使用MyBatis Plus提供的服务进行操作:

@Service

public class UserService {

    @Autowired

    private UserMapper userMapper;

    public boolean saveUser(User user) {

        return userMapper.insert(user) > 0;

    }

    public List<User> getAllUsers() {

        return userMapper.selectList(null);

    }

}

以上代码展示了如何在Spring Boot 3.0项目中集成MyBatis Plus。你需要替换数据库连接信息、实体类、Mapper接口和你的应用包路径。这样,你就可以使用MyBatis Plus提供的方法来简化数据库操作。

;