(1) 区别:
首先清楚一点,动态 SQL 是 mybatis 的强大特性之一,在 mapper 中定义的参数传到 xml 中之后,在查询之前 mybatis 会对其进行动态解析,#{} 和 ${} 在预编译中的处理是不一样的:
例如:select * from t_user where userName = #{name};
#{}预编译:用一个占位符 ? 代替参数:select * from t_user where userName = ?
#{}预编译:会将参数值一起进行编译:select * from t_user where userName = 'zhangsan'
(2) 使用场景:
一般情况首选#{},因为这样能避免sql注入;如果需要传参 动态表名、动态字段名时,需要使用${}
比如:select * from ${tableName} where id > #{id};
(3) SQL注入问题:
举个例子,如果使用${}出现的注入问题:
select * from ${tableName};
如果传参 t_user;delete from t_user,则预编译后的sql如下,将会导致系统不可用:
select * from t_user;delete from t_user;
(4) like 语句防注入:
使用concat函数:
select * from t_user where name like concat('%', #{name}, '%')
2 mybatis几种传参方式
非注解:
(1)单参数:
public User getUserByUuid(String uuid);
SELECT * FROM t_user WHERe uuid = #{uuid}
(2)多参数
public User getUserByNameAndPass(String name,String pass);
2 choose when otherwise
//JAVA 代码
public List getUserRoleRelByUserUuid(@Param("groupUuid") String userUuid,@Param("roleList")List roleUuidList);
//SQL
SELECT * from user_role where groupUuid=#{groupUuid}
AND roleUuid IN
#{roleUuid}
AND roleUuid IN ('')
3 判断字符串相等
//JAVA 代码
public int getOrderCountByParams(Map params);
//SQL
SELECT count(*) FROM itil_publish_order where 1=1
AND create_time >= #{timeStr}
AND end_time <= #{timeStr}
或者
4 CONCAT函数实现 模糊匹配
SELECT count(*) FROM
itil_publish_order
WHERe serial_code LIKE CONCAt('%',#{codeStr},'%')
ORDER BY serial_code DESC LIMIT 1
5 大于等于、小于等于
//JAVA代码
public List getOrderCount(@Param("startTime") String startTime,@Param("startTime")List startTime);
//SQL
SELECT * FROM itil_publish_order
WHERe createTime >= #{startTime} and <= #{startTime}