什么是动态SQL?
动态SQL是指根据不同条件生成不同的SQL语句
IF:
<select id="getBlogIf" 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):
<select id="getBlogChoose" resultType="blog" parameterType="map">
select * from mybatis.blog
<where>
<choose>
<when test="title != null">
title=#{title}
</when>
<when test="author!=null">
author=#{author}
</when>
<otherwise>
views=#{views}
</otherwise>
</choose>
</where>
</select>
按顺序,when里面哪个存在就用哪个
where标签:
处理“1=1”,and/or,where的问题
set标签:当使用update语句时需要用到set,用set标签可以当在里面使用if标签时去掉多余的逗号,但不会添加逗号
trim标签:
sql片段:
用sql标签写上一段sql语句,在需要引用的地方用include标签引用
<sql id="if-author">
<if test="title != null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</sql>
<select id="getBlogIf" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<include refid="if-author"/>
</where>
用sql片段可以实现代码的复用;
最好基于单表定义sql片段;不要存在where标签
foreach标签:
属性:
collection:传入一个集合,对其进行遍历
item:每个元素的名称
open:结果以什么开头
close:结尾
seperator:分隔符
<select id="getBlogForeach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" index="index" item="id" open="(" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
public void getBlogForeach(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap hashMap = new HashMap();
ArrayList<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
hashMap.put("ids",ids);
List<Blog> blogs = mapper.getBlogForeach(hashMap);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
如上:传入一个"ids"集合,foreach遍历集合的每一个元素,最终实现的sql语句为:
==> Preparing: select * from mybatis.blog WHERE ( id=? or id=? )
==> Parameters: 1(Integer), 2(Integer)