今天在作一個in查詢時,涉及到排序的問題。html
<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,java
<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字符串的時候,要用${}在拼接,由於${}與#{}的一個很大不一樣之處,在於${}只是一個簡單的取值,而#{}的取值會帶來 '',因此形成了,超出索引的這個錯誤。spa
正確的mybatis sql以下code
<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注入的話,只能經過手動寫程序去過濾,進行,防止。htm
問題解決參照:http://www.bkjia.com/Javabc/978196.html排序