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>
此时程序正常。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)