Skip to content

Spring Boot整合MyBatis主要步骤

1. 引入依赖(pom.xml)

  • 引入数据库驱动
  • 引入 MyBatis Starter
  • 引入连接池(默认 HikariCP)
<!-- MySQL驱动 -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>

<!-- MyBatis Spring Boot Starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-boot-starter</artifactId>
    <version>3.0.3</version>
</dependency>

2. 配置文件配置(application.yml)

配置数据源、连接池、MyBatis 全局规则。

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/testdb
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.entity
  configuration:
    map-underscore-to-camel-case: true

3. 开启/扫描配置(启动类或配置类)

使用 @MapperScan 扫描 Mapper 接口。

1
2
3
4
5
6
7
@SpringBootApplication
@MapperScan("com.example.mapper")
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

4. 编写实体类(Entity/Model)

与数据库表对应。

1
2
3
4
5
6
public class User {
    private Long id;
    private String username;
    private Integer age;
    // getter/setter
}

5. 编写 Mapper 接口(DAO 层)

定义数据库操作方法。

1
2
3
4
5
@Mapper
public interface UserMapper {
    User selectById(Long id);
    int insert(User user);
}

6. 编写 XML 映射文件(mapper/*.xml)

编写 SQL,实现接口方法。

1
2
3
4
5
6
7
8
9
<?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.example.mapper.UserMapper">
    <select id="selectById" resultType="User">
        select id, username, age from user where id = #{id}
    </select>
</mapper>

7. 编写 Service 层业务逻辑

注入 Mapper 并封装业务。

1
2
3
4
5
6
7
8
9
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }
}

8. 编写 Controller 接口

对外提供 API。

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User get(@PathVariable Long id) {
        return userService.getUserById(id);
    }
}

9. 自定义配置类(可选扩展)

如自定义 SqlSessionFactory、插件、分页等。

1
2
3
4
5
6
7
8
9
@Configuration
public class MyBatisConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
}

10. 插件/拦截器配置

如分页插件、性能监控、SQL 重写等。 (如上第9点的分页拦截器)

11. 事务管理

使用 @Transactional 控制事务。

1
2
3
4
@Transactional
public void addUser(User user) {
    userMapper.insert(user);
}

12. 日志与 SQL 输出

在 yml 中开启 MyBatis 日志。

1
2
3
logging:
  level:
    com.example.mapper: debug

13. 异常处理

全局异常捕获数据库异常。

1
2
3
4
5
6
7
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLException.class)
    public Result handleSqlException() {
        return Result.fail("数据库异常");
    }
}

14. 多环境配置

application-dev.yml / application-prod.yml 分别配置不同数据库。

15. 测试

使用 @SpringBootTest 测试 Mapper/Service。

@SpringBootTest
public class UserMapperTest {
    @Autowired
    UserMapper userMapper;

    @Test
    void test() {
        System.out.println(userMapper.selectById(1));
    }
}

16. 扩展配置方式(@PropertySource 等)

如需加载自定义 db.properties:

1
2
3
4
@Configuration
@PropertySource("classpath:db.properties")
public class DataSourceConfig {
}