MyBatis · Q & A with Arwen
重要对象
SqlSessionFactory
- 基于配置生成, 因此只需要全局唯一即可 单例
SqlSession
- 带有一级缓存等, 不是线程安全的
- 一次数据库业务产生的会话对象
XML
典型的Mapper XML
代码块收起展开
<mapper namespace="com.demo.UserMapper">
<!-- 查询 -->
<select id="selectById" parameterType="int" resultType="com.demo.User">
select id, name, age
from user
where id = #{id}
</select>
<!-- 插入 -->
<insert id="insertUser" parameterType="com.demo.User" useGeneratedKeys="true" keyProperty="id">
insert into user(name, age)
values(#{name}, #{age})
</insert>
<!-- 动态SQL -->
<select id="list" resultType="com.demo.User">
select * from user
<where>
<if test="name != null">
name = #{name}
</if>
<if test="age != null">
and age = #{age}
</if>
</where>
</select>
</mapper>MappedStatement
- 根据xml解析成的一个结构化对象
- 减少不必要的重复创建对象, 因为sql其实比较固定, 变的是参数
代码块收起展开
编译时
XML(人写的规则)
↓ 解析
MappedStatement(机器用的结构化对象)
//方法运行时
mapper方法调用
↓
找到 MappedStatement
↓
套参数 → 生成最终 SQL
↓
执行Executor
- 调用JDBC执行query/update等---->封装了
PreparedStatement - 管理SqlSession的缓存, 第二次查不走数据库
- 事务的提交、回滚
- 二级缓存, 绑定Mapper / namespace
| simpleExecutor | ReuseExecutor | BatchExecutor |
|---|---|---|
| 每次都新建Statement | PreparedStatement | 攒一攒再批量执行 |