什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句.
IF
<select id="queryBlogIF" parameterType="map" resultType="com.study.pojo.Blog">
select * from mybatis.blog
<where>
<if test="title!=null"><!--可以通过if里面的test值是否为空进行拼接拼接-->
and title =#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</where>
</select>
choose(when,otherwise)
<select id="queryBlogChoose" parameterType="map" resultType="com.study.pojo.Blog">
select * from mybatis.blog
<where>
<choose><!--类似与使用switch——case语句满足那个条件自动匹配哪个-->
<when test="title!=null">
title=#{title}
</when>
<when test="author">
and author=#{author}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
</where>
</select>
<!--choose标签是按顺序判断其内部when标签中的test条件出否成立,如果有一个成立,则 choose 结束。
当 choose 中所有 when 的条件都不满则时,则执行 otherwise 中的sql。
类似于Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。-->
- <where元素的作用是会在写入 <where 元素的地方输出一个 where 语句,
- 不需要考虑 <where元素里面的条件输出是什么样子的,MyBatis 将智能处理
- 如果所有的条件都不满足,那么 MyBatis 就会查出所有的记录,如果输出后是以 and 开头的,MyBatis 会把第一个 and 忽略。
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}
</update>
在动态 update 语句中可以使用 set 元素动态更新列
- 使用SQL标签抽取公共部分,再用include标签引用,方便复用
<sql id="if-title-author" >
<if test="title!=null">
and title =#{title}
</if>
<if test="author!=null">
and author=#{author}
</if>
</sql>
<select id="queryBlogIF" parameterType="map" resultType="com.study.pojo.Blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"></include>
</where>
</select>
- 最好基于单表来定义SQL片段
- 不要存在where标签
foreach
<select id="queryBlogForeach" parameterType="map" resultType="com.study.pojo.Blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
<!--collection集合名字,item集合内单个项的名字
open集合开始的字符例如{ [ (,close集合结束的字符) ] }
separator连接符"or"或者","-->
测试类中的使用
public void queryBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map=new HashMap();
ArrayList<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(2);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
一级缓存默认开启,通过sqlSession.clearCache();可以清理缓存。
作用域在sqlSession的创建到关闭
二级缓存 :
XXXMapper.xml中使用:
<cache eviction="FIFO"
flushInterval="600000"
size="512"
readOnly="true" />
这样也可以使用但是需要将实体类序列化继承Serializable
<cache/>
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效;
- 所有数据都会先放在一级缓存中;
- 只有提交会话,或者关闭会话的时候才会提交到二级缓存中;