mybatis框架order by作为参数传入时失效小坑

mxl中的语句如下

<select id="statToday" resultType="com.dahua.la.business.model.vo.StatSysResultVO">
      select a,
             b,
      		count(1) as total
      from table
      where  a is not null
      and b is not null
      and operateTime >= #{startTime,jdbcType=TIMESTAMP}
      and operateTime <= #{endTime,jdbcType=TIMESTAMP}
      group by a, b
   order by
   <foreach collection="orderItems" item="item" separator=",">
      #{item.orderBy} #{item.order}
   </foreach>
</select>

运行时通过日志打印出sql日志如下

select a, b, count(1) as total 
from table 
where a is not null and b is not null 
and operateTime >= ? and operateTime <= ? 
group by a, b 
order by ? ?

把参数补充上拿到Navicat执行的时候,完全没有问题,排序也正常。但是在代码里执行就是不行, 最后的排序完全没有生效。

实际上,我补上参数的时候漏了引号,因为#{item.orderBy}会对传入的数据加一个引号,如果带着引号去Navicat执行,也是排序不生效的。问题原因找到了。直接替换成使用${item.orderBy}形式,单纯的字符串替换不加引号。

<foreach collection="orderItems" item="item" separator=",">
    ${item.orderBy} ${item.order}
</foreach>

此时程序正常。

猜你喜欢

转载自blog.csdn.net/u013041642/article/details/107471905