Mybatis动态SQL之IF语句详解
更新时间:2021年05月06日 14:48:01 作者:TheLightOfCode
这篇文章主要给大家介绍了关于Mybatis动态SQL之IF语句的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
Mysql 5.0 以后,支持了动态sql语句,我们可以通过传递不同的参数得到我们想要的值.
1. Mybatis–动态SQL之IF语句
1.1 BlogMapper.java
// 查询博客
List<Blog> queryBlogIf(Map map);
1.2 BlogMapper.xml
<select id="queryBlogIf" 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>
1.3 Test.java
1.3.1 第一种情况,不加任何查询条件,默认会把所有数据查出来
// 第一种情况,不加任何查询条件,默认会把所有数据查出来
@org.junit.Test
public void test01() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}
运行结果:
查询出了所有记录

1.3.2 第二种情况,添加参数title
@org.junit.Test
public void test01() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
map.put("title", "Spring");
List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}
查询出了一条记录

1.3.3 第三种情况,添加2个参数
@org.junit.Test
public void test01() {
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map map = new HashMap();
map.put("title", "微服务");
map.put("author", "天天天");
List<Blog> blogs = mapper.queryBlogIf(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}

总结
到此这篇关于Mybatis动态SQL之IF语句的文章就介绍到这了,更多相关Mybatis动态SQL IF语句内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
springmvc HttpServletRequest 如何获取c:forEach的值
这篇文章主要介绍了springmvc HttpServletRequest 如何获取c:forEach的值方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-08-08
详解spring集成mina实现服务端主动推送(包含心跳检测)
本篇文章主要介绍了详解spring集成mina实现服务端主动推送(包含心跳检测),具有一定的参考价值,与兴趣的可以了解一下2017-09-09


最新评论