Mybaits 查询 choose when 的使用

@Select("<script>"+
                              "SELECT * " +
                              "FROM bgs_housing A" +
                              " <where> " +
                              " A.building !=0  and built_area >=#{needVo.min_acreage}  and  built_area <= #{needVo.max_acreage}  and built_area !=0"+
                              " and A.id NOT IN(SELECT housing FROM bgs_follow WHERE need = #{needVo.id} AND bgs_follow.state <5)"+
                              " AND  A.type = #{needVo.max_acreage}"+
                              " <foreach collection=\"params.keys\" item=\"key\"   > "+
                         "    <choose>\r\n" +
                         "        <when test=\"key =='name'\">\r\n" +
                        "           and A.name like concat('%',#{params[${key}]},'%') " +
                        "        </when>\r\n" +
                        "        <otherwise>\r\n" +
                            "       <if test=\"params[key]!= null\">and  A.${key} =#{params[${key}]}</if> " +
                         "        </otherwise>\r\n" +
                        "    </choose>"+
                              "</foreach>  "+
                              " <if test=\"needVo.min_price!= 0\">and  A.rent_price >=#{needVo.min_price}</if> " +
                              " <if test=\"needVo.max_price!= 0\">and  A.rent_price <=#{needVo.max_price}</if> " +
                              " </where> " +
                              " limit #{page.offset},#{page.size}"+
                               "</script>")
          List<Map<String, Object>> matchHousing(@Param("needVo")Need needVo, @Param("params")Map<String, Object> params,@Param("page") PageUtil page)throws Exception;

注意:

单字符判断相等时错误:

  <if test="takeWay == '1' and workday != null ">
  改为<if test='takeWay == "1" and workday != null '>
  或改为<if test="takeWay == '1'.toString() and workday != null ">即可。
 
原因是:
  mybatis是用OGNL表达式来解析的,在OGNL的表达式中,’1’会被解析成字符,java是强类型的,char 和 一个string 会导致不等,所以if标签中的sql不会被解析。
  总结下使用方法:单个的字符要写到双引号里面或者使用.toString()才行!

posted on 2019-08-15 17:02  滚动的蛋  阅读(407)  评论(0编辑  收藏  举报

导航