动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句
常用标签:
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
通过这些标签,可组合成非常灵活的SQL语句,从而不仅提高 SQL 语句的准确性,也提高了开发人员的效率。
blog表:
现在要查询所有的信息?只用一句sql就可以搞定
select * from blog
如果要求根据输入的title查询书籍?也可以一句搞定
select * from blog where title = #{title}
如果再要求根据作者名查询?那就只能再写一个sql······这样效率变得贼慢,那我怎么实现用一个sql搞定:如果不传参数时,查询出来的是全部信息,输入作者名时,查询出来的是相应作者对应的信息,或者输入title时,出来的又是title对应的信息?这就用到了动态sql。
1. if+where
Mapper接口:
List<Blog> queryBlogIf(Map map);
(为了方便,参数用的是map类型,真是万能map。)
Mapper.xml文件:
<select id="queryBlogIf" parameterType="map" resultType="blog">
select * from blog
<!--where标签只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。-->
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
<!--如果上面的第一个条件不成立,where就会把这个and去掉,sql就变成了select * from blog where author = #{author}-->
and author = #{author}
</if>
</where>
</select>
需要注意的是,“where”标签只有在它包含的标签中有返回值时,才会插入一个‘where’子句。而且,如果标签返回的内容是以AND 或OR 开头的,则它会剔除将它们掉。
测试类:
@Test
public void testQueryIf(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
//不向map中加数据的话,会查询出来所有信息,加上去之后可以查询出想要的信息。不用改sql语句从而实现不同的查询。
map.put("title","mybatis学习");
//map.put("author","小李");
List<Blog> blogList = mapper.queryBlogIf(map);
for (Blog blog : blogList)