今天在做一个in查询时,涉及到排序的问题。
<select id="getStationList" parameterType="java.util.List"
resultType="com.bus.pojo.Station">
SELECT * FROM `station` WHERE id in
<foreach collection="list" item="item" index="index" open="("
separator="," close=")">
#{item}
</foreach>
and locked = '0'
</select>
上sql时查询时,希望返回来的数据,按照in的顺序,返回来。一开始,因为使用#{}在第二条foreach中取值,进行,拼接,排序的order by,
<select id="getStationList" parameterType="java.util.List"
resultType="com.bus.pojo.Station">
SELECT * FROM `station` WHERE id in
<foreach collection="list" item="item" index="index" open="("
separator="," close=")">
#{item}
</foreach>
and locked = '0' ORDER BY SUBSTRING_INDEX (
<foreach collection="list" item="item" index="index" open="'"
separator="," close="'">
#{item}
</foreach>
, id, 1)
</select>
但是,控制台报错,错误如下
### SQL: SELECT * FROM `station` WHERE id in ( ? , ? , ? ) and locked = '0' ORDER BY SUBSTRING_INDEX
( ' ? , ? , ? ' , id, 1)
### Cause: java.sql.SQLException: Parameter index out of range (4 > number of parameters, which is 3).
; SQL []; Parameter index out of range (4 > number of parameters, which is 3).; nested exception is java.sql.SQLException:
Parameter index out of range (4 > number of parameters, which is 3).] with root cause
java.sql.SQLException: Parameter index out of range (4 > number of parameters, which is 3).
超出了索引,百思不得其解
到后来上百度,查找原因,才知道:
在拼接sql字符串的时候,要用${}在拼接,因为${}与#{}的一个很大不同之处,在于${}只是一个简单的取值,而#{}的取值会带来 '',所以造成了,超出索引的这个错误。
正确的mybatis sql如下
<select id="getStationList" parameterType="java.util.List" resultType="com.bus.pojo.Station">
SELECT * FROM `station` WHERE id in
<foreach collection="list" item="item" index="index" open="("
separator="," close=")">
#{item}
</foreach>
and locked = '0' ORDER BY SUBSTRING_INDEX (
<foreach collection="list" item="item" index="index" open="'" separator="," close="'">
${item}
</foreach>
, id, 1)
</select>
在正常的使用当中,为了防止sql注入,尽量使用#{},避免 ${},如果使用了${}需要防止sql注入的话,只能通过手动写程序去过滤,进行,防止。
问题解决参照:http://www.bkjia.com/Javabc/978196.html