Spring Boot3.3.X整合Mybatis-Plus
在Spring Boot 3.3.X整合MyBatis-Plus,你需要做以下几个步骤:
- 在pom.xml中添加MyBatis-Plus的依赖:
<dependencies>
<!-- 其他依赖... -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.X</version>
</dependency>
<!-- 数据库驱动依赖,例如MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.X.X</version>
</dependency>
</dependencies>
- 配置application.properties或application.yml文件,添加数据库连接信息和MyBatis-Plus相关配置:
# application.properties
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
mybatis-plus.global-config.db-config.id-type=auto
mybatis-plus.global-config.db-config.field-strategy=not_empty
mybatis-plus.global-config.db-config.table-prefix=tbl_
- 创建Mapper接口和对应的Mapper XML文件。
// UserMapper.java
package com.yourpackage.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yourpackage.model.User;
public interface UserMapper extends BaseMapper<User> {
// 自定义CRUD操作的方法(如果需要)
}
<!-- UserMapper.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yourpackage.mapper.UserMapper">
<!-- 自定义SQL语句 -->
</mapper>
- 在Spring Boot启动类上添加@MapperScan注解,扫描Mapper接口:
// YourApplication.java
package com.yourpackage;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.yourpackage.mapper")
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
- 使用MyBatis-Plus提供的方法进行CRUD操作。
// SomeService.java
package com.yourpackage.service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yourpackage.mapper.Us
评论已关闭