需求
要求:传递title就按照title查询,传递author就按照author查询,什么都不传递就都查询出来
需求分析
我们在数据库中使用SQL语句实现上面的需求就是在传入title就加上title的where子句,传入author就加上author的子句,什么都不传就整表查询
代码实现
- 接口
package com.thhh.dao; import com.thhh.pojo.Blog; import java.util.List; import java.util.Map; public interface BlogMapper { //1、添加一条博客信息 int addBlog(Blog blog); //2、使用IF来查询博客 List<Blog> qureryBlogIf(Map<String,Object> map); }
- mapper.xml
<select id="qureryBlogIf" 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>
- 测试
- 传入title参数
@Test public void testQureryBlogIf(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Map<String,Object> map = new HashMap<String,Object>(); map.put("title","标题3"); List<Blog> blogList = mapper.qureryBlogIf(map); for (Blog blog : blogList) { System.out.println(blog); } sqlSession.close(); }
- 传入title参数
- 传入author参数
@Test public void testQureryBlogIf(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); BlogMapper mapper = sqlSession.getMapper(BlogMapper.class); Map<String,Object> map = new HashMap<String,Object>(); map.put("author","作者2"); List<Blog> blogList = mapper.qureryBlogIf(map); for (Blog blog : blogList) { System.out.println(blog); } sqlSession.close(); }
- 不传入参数
@Test
public void testQureryBlogIf(){
SqlSession sqlSession = MyBatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Map<String,Object> map = new HashMap<String,Object>();
// map.put("author","作者2");
List<Blog> blogList = mapper.qureryBlogIf(map);
for (Blog blog : blogList) {
System.out.println(blog);
}
sqlSession.close();
}
小结
① 上面的例子就是mybatis的if标签的使用,其实可以看出和JSTL的if使用方式一样,通过使用IF语句我们就可以实现原来SMBMS中按照姓名查询数据和按照职位查询数据的功能
②原来手写JDBC我们需要写大量的代码来实现这个功能,现在使用mybatis的if标签就实现了SQL语句的复用和动态添加
注意