mybatis的#{} ${} 的区别

本文介绍在MyBatis中如何正确实现IN查询并按传入ID顺序排序,解决了使用#{}

今天在做一个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

转载于:https://my.oschina.net/xbuding/blog/646949

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值