在上一章中的介绍if 标签时,其实我们发现了一个问题,就是当所有条件都为空时,sql语句会多出来一个where,而且有时候会多出来一个and等等。
而where标签的作用就是为了解决这类问题,where 标签可以自动去除多余的where,and,or这类语句,它是专门管理where子句,可以使其更加灵活。
我们继续沿用上一章的if 标签基础上进行更改代码。
mapper接口如下:
// 动态sql--where 标签
List<Book> findBookBySqlWhere(@Param("bname") String bname ,@Param("price") Double price ,@Param("cid") String cid ) ;
因为在上一章<if>标签中,已经对代码内容解释过了,所以这里就不在赘述代码了。
mapper映射文件的sql语句如下:
<!-- 动态sql(where标签)-->
<select id="findBookBySqlWhere" resultType="com.feisi.mybatis.pojo.Book">
select * from t_book
<where>
<if test="bname != null and bname != ''">
and bname like "%"#{bname}"%"
</if>
<if test="price != null and price != ''">
and price>#{price}
</if>
<if test="cid != null and cid != ''">
and cid = #{cid}
</if>
</where>
这里其他的地方都没有改变,就是将原来的原生where改成了mybatis中的<where>标签,它管理着where标签里面的所有子句。
那么接下来我们对其进行测试代码如下:
public void findBookBySqlWhereTest(){
SqlSession sqlSession = SqlSessionUtil.openSession();
BookMapper mapper = sqlSession.getMapper(BookMapper.class);
// 三个参数都为空时sql语句:select * from t_book
// 他会自动去掉多余出来的where
// List<Book> books = mapper.findBookBySqlWhere("" ,null,"");
// 第一不为空时的sql语句:select * from t_book WHERE bname like "%"?"%"
// 他会自动去掉第一个多余出来的and
List<Book> books = mapper.findBookBySqlWhere("怡宝" ,null,"");
for(Book book : books) System.out.println("查询到:"+book);
sqlSession.close();
}
在上面的测试语句中可以看到,where标签已经帮我自动删除了多余的where,and,当然or也可以去除。
另外需要注意一点就是,where标签它只能去除写在前面的and,如果你把and语句写在后面,比如这样:
那么这样的话,where是不能去除多余的and的。