MyBatis(四)
MyBatis(四)
动态SQL
- 根据不同的条件生成不同的SQL语句
SQL片段
<sql id="sqlid">
...
</sql>
<include refid="sqlid"></include>
- 最好基于表单来定义SQL片段
- 不要用where标签,尽量只用if标签
if
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from mybatis.blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
choose,when,otherwise
- 类似switch,case,default
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
trim,where,set
- where:自动删and
<select id="queryBlogIf" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
# 等价于
<trim prefix="where" prefixOverride="and | or">
...
</trim>
</select>
- set:自动删逗号
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
</set>
where id = #{id}
# 等价于
<trim prefix="set" suffixOverride=",">
...
</trim>
</update>
- trim:前缀prefix、后缀suffix、前缀覆盖prefixOverride、后缀覆盖suffixOverride
foreach
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id"
open="and (" separator="or" close=")">
id = #{id}
</foreach>
</where>
</select>
缓存
简洁
- 存在内存中的临时数据,将用户经常查询的数据放在缓存中,减少和数据库的交互次数,减少系统开销,提高系统效率,解决高并发系统的性能问题
MyBatis缓存
-
默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启(SqlSession级别的缓存,也成为了本地缓存)
- 二级缓存需要手动开启和配置,是基于namespace级别的缓存
- 可以通过实现Cache接口自定义二级缓存
-
缓存清除策略:
- LRU(默认):最近最少使用,移除最长时间不被使用的对象
- FIFO:先进先出,按对象进入缓存的顺序来移除它们
- SOFT:软引用,基于垃圾回收器状态和软引用规则移除对象
- WEAK:弱引用,更积极地基于垃圾回收器状态和弱引用规则移除对象
一级缓存
- 一级缓存也叫本地缓存
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
二级缓存
-
二级缓存也叫全局缓存
-
一个namespace对应一个二级缓存
-
工作机制:
- 会话关闭后,一级缓存中的数据被保存到二级缓存
- 新的会话查询信息,就可以从二级缓存中获取内容
- 不同的mapper查出的数据会放在自己对应的缓存中
-
在配置文件中显式开启全局缓存(默认开启)
<setting name="cacheEnable" value="true"/>
- 在Mapper.xml文件中添加cache标签
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
- 单个查询中设置缓存(默认开启)
<select useCache="true">
</select>
缓存原理
- 先看二级缓存
- 再看一级缓存
- 最后查询数据库
自定义缓存
- 第三方缓存:Ehcache
- 导包,cache标签写type,写配置文件
- 自定义缓存:实现Cache接口
- Redis:K-V键值对做缓存

浙公网安备 33010602011771号