MyBatis 详解及代码示例
MyBatis 是一个 半自动 ORM 框架,主要用于 Java 与数据库之间的持久化操作,它本质是对 JDBC 的封装
- 全名:MyBatis(前身 iBATIS)
- 核心作用:自动将 SQL 执行结果映射为 Java 对象;也可以将 Java 对象自动转成 SQL 参数
- 特点:
- SQL 写在 XML 或注解中,开发者可控制 SQL 逻辑(相比 Hibernate 更灵活)
- 支持参数映射、结果映射
- 支持动态 SQL(根据条件生成 SQL)
🏗️ 1. 在 SpringMVC 项目中的使用步骤
🌱 一、技术栈说明
- Spring MVC(控制层)
- MyBatis(持久层)
- Spring(IoC、事务管理)
- MySQL 数据库
- Maven 构建
🧱 二、项目结构示意(SpringMVC 示例)
spring-mybatis-demo/
├── src/main/java/
│ ├── com.example.controller/ # 控制层
│ ├── com.example.service/ # 业务逻辑
│ ├── com.example.mapper/ # MyBatis Mapper 接口
│ ├── com.example.model/ # 实体类
│ └── com.example.config/ # 配置类(可选)
├── src/main/resources/
│ ├── mapper/ # MyBatis XML 映射文件
│ ├── spring-mybatis.xml # 核心整合配置
│ └── db.properties # 数据源配置
├── webapp/
│ ├── WEB-INF/
│ │ ├── jsp/ # 视图层 JSP
│ │ └── web.xml # Web 配置
└── pom.xml
📦 三、核心配置文件
3.1 pom.xml
(关键依赖)
<dependencies>
<!-- Spring 核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.30</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.15</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.1.1</version>
</dependency>
<!-- MySQL 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- 其他:日志、JSTL、Servlet 等 -->
</dependencies>
3.2 db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/testdb
jdbc.username=root
jdbc.password=123456
3.3 spring-mybatis.xml
(Spring + MyBatis 整合配置)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="...">
<!-- 1. 读取属性配置 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 2. 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 3. 配置 SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
<property name="typeAliasesPackage" value="com.example.model"/>
</bean>
<!-- 4. Mapper 接口扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
<!-- 5. 扫描 Service、Controller -->
<context:component-scan base-package="com.example"/>
<!-- 6. 事务管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
3.4 web.xml
配置 Spring MVC 和核心监听器
<web-app ...>
<!-- Spring 容器监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- Spring MVC 核心配置 -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
💻 四、代码示例
4.1 实体类 User.java
public class User {
private Integer id;
private String name;
private Integer age;
// Getter / Setter
}
4.2 Mapper 接口 UserMapper.java
java复制编辑public interface UserMapper {
User selectById(Integer id);
List<User> selectAll();
}
4.3 Mapper XML 文件 UserMapper.xml
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectById" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
<select id="selectAll" resultType="User">
SELECT * FROM user
</select>
</mapper>
4.4 Service 类
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUser(Integer id) {
return userMapper.selectById(id);
}
public List<User> getAllUsers() {
return userMapper.selectAll();
}
}
4.5 Controller 类
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/list")
public String list(Model model) {
List<User> users = userService.getAllUsers();
model.addAttribute("users", users);
return "userList"; // 对应 userList.jsp
}
}
4.6 JSP 页面(视图层)userList.jsp
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<body>
<h2>User List</h2>
<table border="1">
<tr><th>ID</th><th>Name</th><th>Age</th></tr>
<c:forEach var="u" items="${users}">
<tr>
<td>${u.id}</td>
<td>${u.name}</td>
<td>${u.age}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
💡 五、动态 SQL 示例(补充)
可以在 UserMapper.xml
中这样写:
<select id="searchUser" resultType="User">
SELECT * FROM user
<where>
<if test="name != null and name != ''">
AND name LIKE CONCAT('%', #{name}, '%')
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
调用时只传入某些字段,MyBatis 会自动拼接对应 SQL 语句。
📌 六、总结
内容 | 说明 |
---|---|
Spring MVC | 控制器接收请求,返回视图 |
MyBatis | 封装了 JDBC,实现 SQL 到 Java 映射 |
配置方式 | XML 文件整合(spring-mybatis.xml 、mapper.xml ) |
特点 | 灵活、轻量、适合手写 SQL |
在 SpringBoot 项目中的使用步骤
一、项目结构
1.1 引入依赖(Maven)
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
1.2 配置 application.yml
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.model
configuration:
map-underscore-to-camel-case: true
2.3 编写实体类
public class User {
private Integer id;
private String name;
private Integer age;
// getter/setter...
}
2.4 编写 Mapper 接口
@Mapper
public interface UserMapper {
User selectUserById(Integer id);
List<User> selectAllUsers();
}
2.5 编写 Mapper.xml(放在 resources/mapper/UserMapper.xml
)
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectUserById" resultType="User">
SELECT * FROM user WHERE id = #{id}
</select>
<select id="selectAllUsers" resultType="User">
SELECT * FROM user
</select>
</mapper>
2.6 Service 和 Controller 层调用
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUser(Integer id) {
return userMapper.selectUserById(id);
}
}
⚙️ 2. 配置文件详解(MyBatis 配置)
除了 application.yml
中配置项,MyBatis 也支持独立 XML 配置(mybatis-config.xml
),示例:
<configuration>
<settings>
<!-- 驼峰命名自动映射 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<package name="com.example.model"/>
</typeAliases>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
这些配置项在 Spring Boot 项目中一般都写在 application.yml
里
🧱 3. 核心组件说明
组件 | 作用说明 |
---|---|
SqlSession | MyBatis 的 SQL 会话对象,封装了 JDBC 操作 |
Mapper 接口 | 定义与数据库交互的方法 |
XML Mapper 文件 | 定义 SQL 语句,与接口方法一一对应 |
TypeHandler | 类型处理器,用于 Java 类型与 JDBC 类型互相转换 |
Executor | MyBatis 的 SQL 执行器,控制 SQL 执行流程 |
Configuration | 全局配置对象,保存所有配置信息 |
🧠 4. 动态 SQL(重点)
动态 SQL 是 MyBatis 的亮点之一,常用标签如下:
4.1 <if>
<if test="name != null">
AND name = #{name}
</if>
4.2 <where>
自动拼接 WHERE,去掉多余 AND/OR:
<where>
<if test="name != null"> AND name = #{name} </if>
<if test="age != null"> AND age = #{age} </if>
</where>
4.3 <set>
用于动态生成 UPDATE SET
,避免多余逗号:
<set>
<if test="name != null"> name = #{name}, </if>
<if test="age != null"> age = #{age} </if>
</set>
4.4 <foreach>
用于 IN
查询等场景:
<foreach collection="idList" item="id" open="(" separator="," close=")">
#{id}
</foreach>
4.5 <choose>
<when>
<otherwise>
<choose>
<when test="type == 'admin'"> AND role = 'ADMIN' </when>
<otherwise> AND role = 'GUEST' </otherwise>
</choose>
✅ 5. 优缺点总结
✅ 优点
- SQL 可控,适合复杂业务
- 支持动态 SQL、注解与 XML 并存
- 易于与 Spring/Spring Boot 集成
- 性能好,轻量级
❌ 缺点
- SQL 手写多,维护成本高
- 不支持完整的 ORM 功能(不像 Hibernate 自动生成表结构)