引言
MyBatis 是一个优秀的持久层框架,它消除了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的工作。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
对于想要快速掌握SQL映射与动态SQL的16岁小朋友来说,MyBatis 是一个很好的选择。下面,我们将从入门到精通,一步步带你了解和使用 MyBatis。
一、入门篇
1.1 MyBatis 简介
MyBatis 遵循约定优于配置(约定大于配置)的原则,通过 XML 或注解的方式配置 SQL 映射,将接口和 Java 对象映射成数据库中的记录。
1.2 环境搭建
下载 MyBatis:从 MyBatis 官网下载最新版本的 MyBatis。
添加依赖:在项目的
pom.xml文件中添加 MyBatis 依赖。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
- 配置 MyBatis:在项目的
src/main/resources目录下创建mybatis-config.xml文件,配置数据源、事务管理器等。
<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=""/>
</dataSource>
</environment>
</environments>
</configuration>
1.3 编写 Mapper 接口
创建一个 Mapper 接口,定义需要执行的 SQL 语句。
public interface UserMapper {
List<User> findAll();
}
1.4 编写 Mapper XML
在 src/main/resources 目录下创建对应的 Mapper XML 文件,配置 SQL 映射。
<mapper namespace="com.example.mapper.UserMapper">
<select id="findAll" resultType="com.example.entity.User">
SELECT * FROM user
</select>
</mapper>
二、进阶篇
2.1 动态 SQL
MyBatis 提供了动态 SQL 功能,可以方便地实现条件查询、分页查询等。
<if>标签:根据条件判断是否执行 SQL 语句。
<select id="findUsersByCondition" resultType="com.example.entity.User">
SELECT * FROM user
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
<choose>标签:类似于 Java 中的switch语句。
<select id="findUsersByCondition" resultType="com.example.entity.User">
SELECT * FROM user
<where>
<choose>
<when test="name != null">
name = #{name}
</when>
<when test="age != null">
age = #{age}
</when>
<otherwise>
1 = 1
</otherwise>
</choose>
</where>
</select>
<foreach>标签:用于处理集合类型的参数。
<select id="findUsersByIds" resultType="com.example.entity.User">
SELECT * FROM user
WHERE id IN
<foreach item="id" collection="list" open="(" separator="," close=")">
#{id}
</foreach>
</select>
2.2 一对一、一对多关联查询
MyBatis 支持一对一、一对多关联查询,通过配置 <resultMap> 标签实现。
<mapper namespace="com.example.mapper.UserMapper">
<resultMap id="userMap" type="com.example.entity.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<association property="address" javaType="com.example.entity.Address">
<id property="id" column="address_id"/>
<result property="street" column="street"/>
<result property="city" column="city"/>
</association>
</resultMap>
<select id="findUserById" resultMap="userMap">
SELECT u.id, u.name, u.age, a.id AS address_id, a.street, a.city
FROM user u
LEFT JOIN address a ON u.address_id = a.id
WHERE u.id = #{id}
</select>
</mapper>
三、精通篇
3.1 高级映射
MyBatis 支持多种高级映射,如集合映射、选择映射、延迟加载等。
- 集合映射:用于处理多对多关联查询。
<resultMap id="userMap" type="com.example.entity.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<collection property="orders" ofType="com.example.entity.Order">
<id property="id" column="order_id"/>
<result property="orderNo" column="order_no"/>
<result property="amount" column="amount"/>
</collection>
</resultMap>
- 选择映射:根据条件选择不同的结果。
<select id="findUserById" resultMap="userMap">
SELECT u.id, u.name, u.age,
<choose>
<when test="selectAddress">
a.id AS address_id, a.street, a.city
</when>
<otherwise>
NULL AS address_id, NULL AS street, NULL AS city
</otherwise>
</choose>
FROM user u
LEFT JOIN address a ON u.address_id = a.id
WHERE u.id = #{id}
</select>
- 延迟加载:在查询主表数据时,延迟加载关联表数据。
<select id="findUserById" resultMap="userMap">
SELECT u.id, u.name, u.age
FROM user u
WHERE u.id = #{id}
</select>
<select id="findAddressById" resultMap="addressMap">
SELECT * FROM address
WHERE id = #{id}
</select>
3.2 插件开发
MyBatis 插件可以扩展 MyBatis 的功能,如分页插件、日志插件等。
- 实现 MyBatis 插件接口。
public class PaginationInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 分页逻辑
return invocation.proceed();
}
}
- 注册插件。
SqlSessionFactory sqlSessionFactory = ...;
sqlSessionFactory.getConfiguration().addInterceptor(new PaginationInterceptor());
结语
通过本文的介绍,相信你已经对 MyBatis 有了一定的了解。MyBatis 是一个功能强大的持久层框架,可以帮助你快速实现 SQL 映射与动态 SQL。希望本文能帮助你入门、进阶,最终精通 MyBatis。
