mybatis的#{} ${} 的区别

今天在作一个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排序

相关文章
相关标签/搜索