利用动态Sql实现方法重载
1.当我们遇到方法重载的时候,在JavaWeb阶段由于要写不同的sql语句,只能写两个方法,去写不同的sql语句,但是当学完mybatis之后就可以解决这个问题了,如下面的例子。
public List<Book> queryForPageItems(@Param("begin") int begin, @Param("pageSize")int pageSize);
public List<Book>queryForPageItems(@Param("begin") int begin, @Param("pageSize") int pageSize,@Param("max") int max,@Param("min") int min);
两个方法名相同参数不同,因为对应的sql语句中的填入不同就要写不同的sql,利用动态sql 可以完美的解决
<select id="queryForPageItems" parameterType="int" resultType="Book">
select * from book.t_book
<where>
<if test="min!=null">
<if test="max!=null">
price between #{min} and #{max}
</if>
</if>
</where>
limit #{begin} ,#{pageSize}
</select>
这个是我第一次写的,但是搜索出来没结果,可能是由于,min,和max没有很好的判断,而导致空where,或者别的原因也不怎么清楚,所以换了另一种思路。
<select id="queryForPageItems" parameterType="int" resultType="Book">
select * from book.t_book
<choose>
<when test="min !=0 and max != 0">
where price between #{min} and #{max} limit #{begin} ,#{pageSize}
</when>
<otherwise>
limit #{begin} ,#{pageSize}
</otherwise>
</choose>
这种就不会出错了,直接把where放在里面。执行成功。
2.但是我的项目的另外两个方法的重载用第一种方式却没事。
public Integer queryForPageTotalCount();
public Integer queryForPageTotalCount(@Param("max") int max,@Param("min") int min);
<select id="queryForPageTotalCount" parameterType="int" resultType="int">
select count(*) from book.t_book
<where>
<if test="min!=null">
<if test="max!=null">
price between #{min} and #{max}
</if>
</if>
</where>
</select>
所以动态sql还是很好用的,很好的解决重载的问题,让sql 对应的方法更加灵活。