Mybatis-Plus在控制台打印SQL语句和#{}, ${}之间的区别
使用Mybatis-Plus时, 在控制台打印SQL语句
只需要在 application.yml中加入如下的配置即可:
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
效果如下所示:
==> Preparing: select * from `user` where 1 = 1 and `name` like concat("%", ?, "%");
==> Parameters: w(String)
<== Columns: id, name, age
<== Row: 39a773890a1b12b8a072c1be02ff3cdc, w, 12
<== Row: 3b25fb904548c28b7ac6882d86c7ae5f, w, 12
<== Row: fad61205ca73fb517ca97cc682bc68b9, w, 12
<== Row: fd5921bac71d483cb94db02b77a8a33a, w, 12
<== Total: 4
另外在此次查询中注意到: #{} 与 ${} 之间的区别与使用.
默认情况下, 使用 #{} 参数语法时, MyBatis 会创建 PreparedStatement 参数占位符, 并通过占位符安全地设置参数(就像使用 ? 一样). 这样做更安全, 更迅速, 通常也是首选做法.
不过有时你就是想直接在 SQL 语句中直接插入一个不转义的字符串.
这时候可以考虑使用 ${} 来取值, 不过这时候就有可能出现SQL注入的情况. 解决这种情况的其中一种途径是使用SQL中的
concat(str1, str2, ...)
函数, 将取出的值得两侧加上单引号 ’ 即可. 如
<select id="findByName" resultType="org.wxmx.mybatis_plus_study.entity.User" parameterType="string">
select *
from `user`
where 1 = 1
<if test="name != null and name != ''">
and `name` like concat("%", #{name}, "%");
</if>
</select>