13、《SpringBoot+MyBatis集成(1)——快速入门》
SpringBoot与MyBatis基础整合(1)——快速入门
引言
在Java企业级开发中,Spring Boot凭借其“约定优于配置”的理念大幅简化了项目搭建流程,而MyBatis作为一款优秀的ORM框架,以其灵活的SQL管理能力广受开发者青睐。二者的结合既能享受Spring Boot的便捷,又能保留MyBatis对SQL的精细控制权。本文将从零开始,手把手实现Spring Boot与MyBatis的基础整合,涵盖环境搭建、依赖配置、数据源管理、CRUD操作等核心内容,适合刚接触MyBatis的开发者快速上手。
一、环境搭建与依赖配置
1.1 创建Spring Boot项目
通过Spring Initializr生成项目骨架,选择以下依赖:
- Spring Web(可选,用于后续接口测试)
- MyBatis Framework(核心依赖)
- MySQL Driver(或其他数据库驱动)
或直接在pom.xml
中手动添加依赖:
<!-- MyBatis Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
1.2 配置数据源
在application.yml
中配置数据库连接信息:
spring:
datasource:
url: jdbc:mysql://localhost:3306/test_db?useSSL=false&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
# MyBatis基础配置
mybatis:
mapper-locations: classpath:mapper/*.xml # XML映射文件路径
configuration:
map-underscore-to-camel-case: true # 开启字段驼峰映射
二、Mapper接口与XML映射
2.1 定义实体类与Mapper接口
创建用户实体类User
:
public class User {
private Long id;
private String name;
private Integer age;
// getter/setter省略
}
编写Mapper接口UserMapper
,声明CRUD方法:
@Mapper // 标记为MyBatis接口
public interface UserMapper {
User selectById(Long id);
int insert(User user);
int update(User user);
int deleteById(Long id);
}
2.2 编写XML映射文件
在resources/mapper/UserMapper.xml
中定义SQL:
<?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">
<resultMap id="userMap" type="User">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
</resultMap>
<select id="selectById" resultMap="userMap">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user(name, age) VALUES(#{name}, #{age})
</insert>
<!-- 其他SQL省略 -->
</mapper>
三、核心注解与扫描配置
3.1 @MapperScan注解
若不想在每个Mapper接口上添加@Mapper
,可在启动类添加全局扫描:
@SpringBootApplication
@MapperScan("com.example.mapper") // 指定Mapper接口包路径
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3.2 参数传递与结果映射
- 简单参数:使用
#{param}
占位符,如#{id}
。 - 对象参数:直接引用对象属性,如
#{name}
对应User.name
。 - 结果映射:通过
resultMap
定义数据库字段与实体属性的映射关系(尤其适用于字段名不一致的场景)。
四、单元测试验证功能
编写测试类验证CRUD操作:
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
void testInsert() {
User user = new User();
user.setName("John");
user.setAge(30);
userMapper.insert(user);
Assertions.assertNotNull(user.getId());
}
@Test
void testSelect() {
User user = userMapper.selectById(1L);
Assertions.assertEquals("John", user.getName());
}
}
五、常见问题与解决方案
-
Mapper接口无法注入
- 检查
@MapperScan
路径是否正确。 - 确认XML文件是否位于
resources/mapper
目录下。
- 检查
-
SQL语句执行报错
- 检查XML中
namespace
是否与接口全限定名一致。 - 确认SQL语法是否符合数据库方言。
- 检查XML中
-
字段映射失败
- 开启
map-underscore-to-camel-case
自动转换下划线命名。 - 使用
resultMap
手动定义复杂映射。
- 开启
总结
本文通过一个完整的用户管理案例,实现了Spring Boot与MyBatis的基础整合,涵盖了依赖配置、数据源管理、Mapper接口与XML映射的核心知识点。读者可在此基础上进一步探索动态SQL、事务管理、缓存机制等高级特性。后续将推出系列文章,逐步深入MyBatis的复杂场景应用。