使用mybatis的一个坑

来源:互联网 发布:南京网络品牌推广 编辑:程序博客网 时间:2024/06/06 17:12

刚刚在使用mybatis写sql,一开始我定义了一个接口:

List<Video> getVideosByCondition(@Param("keyword") String keyword, @Param("status") List<String> status,            @Param("deptId") Integer deptId, @Param("userId") String userId,            @Param("categoryId") Integer categoryId, @Param("isDeleted") String isDeleted,            @Param("index") Integer index, @Param("size") Integer size);

然后xml的写法:

        <select id="getVideosByCondition" resultType="com.ovp.domain.Video">            select * from video    where 1=1    <if test="keyword != null and keyword.length()>0">      and ( title like CONCAT('%', #{keyword,jdbcType=VARCHAR}, '%' )        or tag1 like CONCAT('%', #{keyword,jdbcType=VARCHAR}, '%' )        or videoId = #{keyword,jdbcType=VARCHAR}      )    </if>    <if test="status != null and status.size()>0">       and status in       <foreach item="item" collection="status" separator="," open="(" close=")" index="index">        #{item,jdbcType=VARCHAR}    </foreach>     </if>    <if test="deptId != null ">       and deptId=#{deptId,jdbcType=INTEGER}    </if>    <if test="userId != null and userId.length()>0">    and userId = #{userId,jdbcType=VARCHAR}    </if>    <if test="categoryId != null">    and categoryId=#{categoryId,jdbcType=INTEGER}    </if>    <if test="isDeleted != null and isDeleted.length()>0">    and deleted=#{isDeleted,jdbcType=VARCHAR}    </if>     order by createdTime DESC     <if test="index!=null and size!=null">     limit #{index,jdbcType=INTEGER}, #{size,jdbcType=INTEGER}     </if></select>

接口传递的index和size分别是分页的参数。

然后查询结果一直有误,传递的参数也一直查不出问题。后来打印了输出的sql,发现,index的值一直是1。。。

排查来排查去,最后觉得是xml的问题。终于发现foreach里也有index。

而且当我的status的值是null时,查询没有任何问题。测试了一下发现了原因

我在使用foreach的时候,由于元素有2个,所以index是从0到1赋值,也就是说最后一个循环,index的值时1,

到了下面的limit语句,index其实是复用了上面的变量,所以值仍然是1。所以就一直有问题。。。。

最后我换了index变量为其他值。问题解决。