【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提供的方法来简化数据库操作。

相关推荐
ailab3 小时前
研发人员如何写好 AI 提示词:从“问问题”到“驱动研发闭环”
后端
ltl3 小时前
【大模型基础设施工程】25:大模型基础设施未来
后端
ltl3 小时前
【大模型基础设施工程】二十四:成本、合规与安全
后端
吴爃3 小时前
Spring Boot 项目在 K8S 中的打包、部署与运维发布实践
运维·spring boot·kubernetes
ltl3 小时前
【大模型基础设施工程】22:大模型网关
后端
a8a3023 小时前
Laravel8.x新特性全解析
java·spring boot·后端
白露与泡影3 小时前
Spring Boot 完整流程
java·spring boot·后端
Mr.Rice.Fool4 小时前
rust面试经验1
后端·面试·职场和发展·rust
小鲁蛋儿4 小时前
Dynamic + ShardingSphere整合
spring boot·shardingsphere·dynamic