Mybatis Order by 没有生效

8月 21, 2014 |

select * from student t order by #{orderString}

传值如下:orderString = “t.xCode Desc”

发现查出来的记录是没有排序的,当把select * from student t order by t.xCode Desc 在命令行直接执行的时候,查询出来的结果是排好序的,google了很久才发现, 对了排序不能用#{} 只能用${} ,

#{}的语义是产生preparedStatement :上面的SQL预编译后产生的SQL如下:

select * from student t order by ?

在运行时将?替换为” t.xCode Desc”, mybatis 会安全的处理类型,产生的最终SQL如下:

select * from student t order by ‘t.xCode Desc’ 所以排序失败, 但是该sql能正常运行,至少我在Mysql上执行的结果是这样的,不知是否是mysql 的bug。

 

${}直接进行字符串的替换,产生的SQL 为:

select * from student t order by t.xCode Desc 排序成功

Posted in: Mybatis practise | Tags: ,

Comments are closed.