dmybatis-spring-boot-starter
一个简化 MyBatis 与 Spring Boot 集成的自定义自动配置启动器
项目介绍
该项目提供了一个简化的 MyBatis 与 Spring Boot 集成方案,通过自动配置减少开发者的配置工作,实现开箱即用的 MyBatis 集成体验。
功能特点
- ✅ 自动配置 SqlSessionFactoryBean
- ✅ 自动扫描 Mapper 接口并注册为 Spring Bean
- ✅ 支持自定义 Mapper 扫描包
- ✅ 与 Spring Boot 无缝集成
依赖要求
- Java 8+
- Spring Boot 3.0+
- MyBatis 3.5+
使用方法
1. 添加依赖
在你的 Spring Boot 项目中添加以下依赖:
<dependency>
<groupId>org.oak</groupId>
<artifactId>dmybatis-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
2. 配置数据源
在 application.properties 或 application.yml 中配置你的数据源:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3. 创建 Mapper 接口
在你的项目中创建 Mapper 接口,并使用 @Mapper 注解标记:
package com.example.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import com.example.entity.User;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(Long id);
}
4. 注入并使用 Mapper
在你的 Service 或 Controller 中直接注入并使用 Mapper 接口:
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.mapper.UserMapper;
import com.example.entity.User;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Long id) {
return userMapper.findById(id);
}
}
配置说明
该启动器提供了以下可配置项:
| 配置项 | 描述 | 默认值 |
|---|---|---|
mybatis.mapper-locations | Mapper XML 文件位置 | classpath*:mapper/**/*.xml |
mybatis.type-aliases-package | 实体类包路径 | 自动扫描启动类所在包 |
项目结构
spring-code/
├── dmybatis-spring-boot-autoconfigure/ # 自动配置模块
│ └── src/main/java/org/oak/config/
│ └── MyBatisAutoConfig.java # 核心配置类
├── dmybatis-spring-boot-starter/ # 启动器模块
├── README.md # 项目说明文档
└── LICENSE # 许可证文件