官方文档:MyBatis中文网
一、核心特性
- 半ORM框架:需手动编写 SQL,但自动映射结果集到对象
- 动态SQL:通过 XML 标签动态生成 SQL
- 低学习曲线:相比全自动 ORM 更易掌握
- 高性能:直接操作 SQL,便于优化
二、快速开始
1. 添加依赖(Maven)
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.13</version>
</dependency>
2. 配置文件 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
三、核心组件
1. POJO 实体类
public class User {
private Integer id;
private String name;
private String email;
// Getters & Setters
}
2. Mapper 接口
public interface UserMapper {
User selectUserById(int id);
void insertUser(User user);
void updateUser(User user);
void deleteUser(int id);
}
3. Mapper XML 映射
<!-- UserMapper.xml -->
<mapper namespace="com.example.dao.UserMapper">
<select id="selectUserById" resultType="User">
SELECT * FROM users WHERE id = #{id}
</select>
<insert id="insertUser" parameterType="User">
INSERT INTO users(name, email)
VALUES(#{name}, #{email})
</insert>
</mapper>
四、动态 SQL
1. <if>
条件判断
<select id="findUsers" resultType="User">
SELECT * FROM users
<where>
<if test="name != null">
AND name LIKE #{name}
</if>
<if test="email != null">
AND email = #{email}
</if>
</where>
</select>
2. <foreach>
遍历集合
<select id="selectUsersInIds" resultType="User">
SELECT * FROM users
WHERE id IN
<foreach item="id" collection="ids" open="(" separator="," close=")">
#{id}
</foreach>
</select>
3. <choose>
多分支选择
<select id="findActiveUser" resultType="User">
SELECT * FROM users
<where>
<choose>
<when test="state == 'ACTIVE'">
status = 1
</when>
<when test="state == 'INACTIVE'">
status = 0
</when>
<otherwise>
status IS NOT NULL
</otherwise>
</choose>
</where>
</select>
五、高级功能
1. 结果集映射(ResultMap)
处理复杂字段映射:
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id"/>
<result property="name" column="user_name"/>
<result property="email" column="user_email"/>
</resultMap>
2. 一对一/一对多关联
<resultMap id="userWithOrdersMap" type="User">
<id property="id" column="id"/>
<collection property="orders" ofType="Order">
<id property="orderId" column="order_id"/>
<result property="orderNo" column="order_no"/>
</collection>
</resultMap>
3. 缓存机制
- 一级缓存:SqlSession 级别,默认开启
- 二级缓存:Mapper 级别,需手动开启:
<cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/>
六、Spring Boot 整合
1. 添加依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
2. 配置 application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=123456
mybatis.mapper-locations=classpath:mapper/*.xml
3. 使用 @MapperScan
@SpringBootApplication
@MapperScan("com.example.dao")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
七、最佳实践
- SQL 优化:利用 MyBatis 直接编写高效 SQL
- 参数传递:使用
@Param
注解明确参数名 - 分页处理:集成 PageHelper 插件
- 防止 SQL 注入:避免
${}
使用,优先用#{}
- 日志配置:开启 MyBatis 日志监控 SQL 执行
八、常见问题
- Mapper 未找到:检查 XML 文件路径和 namespace 配置
- 字段映射失败:使用 ResultMap 或别名匹配
- 事务管理:结合 Spring 的
@Transactional
注解 - 延迟加载:在配置文件中设置
lazyLoadingEnabled=true
评论 (0)