从零搭建开发脚手架 Spring Boot集成Mybatis-plus之一
以下是整合MyBatis-Plus到Spring Boot项目的核心步骤:
- 在
pom.xml
中添加MyBatis-Plus的依赖:
<dependencies>
<!-- 其他依赖 ... -->
<!-- MyBatis-Plus -->
<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>
<version>8.x.x</version>
</dependency>
</dependencies>
- 配置
application.properties
或application.yml
文件,添加数据库连接信息:
# 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
- 创建实体类对应数据库表:
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("user")
public class User {
private Long id;
private String name;
private Integer age;
private String email;
// 省略getter和setter方法
}
- 创建Mapper接口:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
// MyBatis-Plus会自动处理CRUD操作
}
- 在Spring Boot启动类上添加
@MapperScan
注解,指定Mapper接口所在的包:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.yourpackage.mapper") // 指定Mapper接口的包路径
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
以上步骤为整合MyBatis-Plus到Spring Boot项目的基本步骤,实际项目中可能还需要配置更多高级功能,如分页插件、全局配置等。
评论已关闭