对于多条件联合查询,可以使用动态SQL之if查询,避免写多个mapper接口多次查询
1、实体类Blog
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
2、BlogMapper接口
public interface BlogMapper {
//查询所有博客信息
List<Blog> getBlog();
//添加博客
int addBlog(Blog blog);
//根据条件查询,SQL if动态查询,因为是动态查询,所有输入参数为map类型
List<Blog> queryBlogIf(HashMap map);
}
3、 mapper.xml
<select id="queryBlogIf" parameterType="map" resultType="com.lizheng.pojo.Blog">
select * from mybatis.blog where 1=1
<if test="title != null">
and title = #{title}
</if>
<if test="author != author">
and author = #{author}
</if>
</select>
4、测试类
@Test
public void queryBlogTest(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("author","狂神说");
map.put("title","Mybatis");
mapper.queryBlogIf(map);
sqlSession.commit();
sqlSession.close();
}
5、运行结果
注意点:SQL中IF标签的使用格式;以及where 1=1 (意思是一定执行) ,如果不加上1=1 ,当执行author的时候,SQL语句变成select * from mybatis.blog and author = #{author} ,这会报错。此时另外一种解决方法就是使用<where><where/>标签。