首先,动态SQL是Mybatis的强大特性之一。利用这一特性可以让我们摆脱根据不同条件拼接SQL语句的痛苦(如拼接SQL语句要确保不能忘记添加必要的空格,还要注意去掉列表里最后一个列名的逗号等等)
这个标签提供了可选的查找文本功能根据是否传入相应的字段来确定要不要把if标签内的语句拼接到主SQL语句。实例:
数据库表:
对应实体类:
@Alias("blog")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class blog {
private int id;
private String title;
private String author;
private Date createTime;
private int views;
}
接口:
public interface blogMapper {
//查找符合条件的blog
List<blog> getblogList(Map<String, Object> map);
}
使用if标签:
Mapper.xml:(里面的1=1是为了引进where后面方便拼接,即使后面if标签内的条件都不符合为空也能符合sql规则)
<select id="getblogList" parameterType="map" resultType="blog">
select blog.id, title, author, createTime, views
from blog
where 1=1
-- 如果有传入title,则将下面的语句拼接到上面的sql语句后面
<if test="title!=null">
and title=#{title}
</if>
-- 同理
<if test="views!=null">
and views=#{views}
</if>
</select>
测试:
@Test
public void fun() {
SqlSession sqlSession = mybatisUtils.getSqlSession();
blogMapper mapper = sqlSession.getMapper(blogMapper.class);
Map map = new HashMap<String, Object>();
// map为空,即我们什么也没有往SQL里面的字段传数值
List<blog> blogs = mapper.getblogList(map);
for (blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
结果如下:可以看出,当我们没有往里面传值时就相当于执行了
select blog.id, title, author, createTime, views from blog
然后返回结果
如果我们传入一个值呢,如下
@Test
public void fun() {
SqlSession sqlSession = mybatisUtils.getSqlSession();
blogMapper mapper = sqlSession.getMapper(blogMapper.class);
Map map = new HashMap<String, Object>();
map.put("title", "java");
List<blog> blogs = mapper.getblogList(map);
for (blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}
结果如下,此时传入的'title'这个字段是不是就不为空了,相当于执行了
select blog.id, title, author, createTime, views from blog where title='java'
如果传入多个值,只要if标签中判断到对应的字段值不为空,那么就会把符合条件的语句拼接到主SQL语句的后面,然后执行。
IF语句加强:
<select id="getblogList2" parameterType="map" resultType="blog">
select blog.id, title, author, createTime, views
from blog
/*将1=1设置成动态条件*/
<where>
<if test="title!=null">
title=#{title}
</if>
<if test="views!=null">
and views=#{views}
</if>
</where>
where 标签元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
测试同上
使用choose-when-otherwise标签
接口同上
Mapper.xml如下:(类似Java里面swich-case语句,传入的值使得when标签内的test内判断成立,就将该when标签内的sql追加到主SQL语句后面,otherwise标签标示如果上面的when都没有一个符合,就默认追加otherwise标签内的语句到主SQL语句)
<select id="getblogList" resultType="blog" parameterType="map">
select *
from blog
where 1=1
<choose>
<when test="title!=null">
and title=#{title}
</when>
<when test="id!=null">
and id=#{id}
</when>
<when test="views!=null">
and views=#{views}
</when>
<otherwise>
/*如果一个参数都没有传,就默认传views=12*/
and views=12
</otherwise>
</choose>
</select>
测试同上,这里不再重复写
学习笔记,记录一下,O(∩_∩)O哈哈~ 如有不对,欢迎指正!!!
觉得不错,三连支持一下哦!!加油!!!