在Mabatis中 ${}与#{}的模糊查询使用占位符号进行功能比较

mac2026-05-04  7

将name的值设置成 Lebron James 使用两种方式分别进行模糊查询

MySQL语句
select * from table_name where user_name like '%${name}%' select * from table_name where user_name like '%#{name}%'
‘%${name}%’ 解析成
select * from table_name where user_name like like '% Lebron James%'
‘%#{name}%’ 解析成
select * from table_name where user_name like '%?%'
但是 ‘%#{name}%’ 解析会发成运行错误
Caused by: org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='sexName', mode=IN, javaType=class java.lang.String, jdbcType=null, numericScale=null, resultMapId='null', jdbcTypeName='null', expression='null'}. Cause: org.apache.ibatis.type.TypeException: Error setting non null for parameter #1 with JdbcType null . Try setting a different JdbcType for this parameter or a different configuration property. Cause: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

可以看出’%#{name}%’ 是无法正确运行,但是使用 ${} 无法防止sql注入 ,所以实际应用时使用 concat函数连接字符串。如 :

select * from table_name where user_name like concat('%',#{name},'%');
最新回复(0)