什么是动态SQL?
动态SQL就是指根据不同条件生成不同的sql语句。
动态SQL元素和JSTL或基于类似XML的文本处理器相似。
在Mybatis之前的版本中,有很多元素需要花时间了解。
Mybatis3大大简化了元素种类,现在只需学习原来一半的元素即可。
Mybatis采用功能强大的基于OGNL的表达式来淘汰其它大部分元素。
if
choose(when,otherwise)
trim(where,set)
foreach
动态SQL之if标签
数据库表结果如下:
查询语句如下:
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</select>
动态SQL之where标签
where 1=1在实际开发当中使用是不合规范的,建议使用where标签:
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
动态SQL之choose(when,otherwise)标签
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
select * from 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>
动态SQL之set标签
<update id="updateBlog" parameterType="map">
update blog
<set>
<if test="title !=null">
title = #{title},
</if>
<if test="author !=null">
author = #{author},
</if>
</set>
where id = #{id}
</update>
SQL片段
有的时候,我们可能会将某些sql语句的部分功能抽取出来,方便复用!
- 使用sql标签抽取公共部分;
<sql id ="if_title-author">
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
- 在需要使用的地方使用include标签引用即可。
<select id="queryBlogIF" parameterType="map" resultType="Blog">
select * from blog
<where>
<include refid="if_title-author"/>
</where>
</select>
提取sql片段注意事项:
- 最好基于单表来定义SQL片段;
- 提取的片段不要包含where标签内容。
动态SQL之foreach标签
<select id="queryBlogForeach" parameterType="map" resultType="Blog">
select * from blog
<where>
<foreach collection="authors" item="Author" open="and (" close=")" separator="or">
author = #{Author}
</foreach>
</where>
</select>
@org.junit.Test
public void testQueryBlogForeach(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
Map map = new HashMap();
ArrayList<String> authors = new ArrayList<>();
authors.add("cyj2");
authors.add("hpf");
map.put("authors",authors);
List<Blog> blogs = sqlSession.getMapper(BlogMapper.class).queryBlogForeach(map);
for(Blog blog : blogs)
System.out.println(blog.toString());
sqlSession.close();
}
总结:
我们可以简单理解动态SQL语句:动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL语句的格式去排列组合就可以了。