MyBatis参数占位符
- #{}:会将其替换为 ?,为了防止SQL注入
<select id="selectById" resultMap="brandResultMap">
select *
from tb_brand where id = #{id};
</select>
得到的SQL语句:select * from tb_brand where id = ?
- ${}:拼sql。会存在SQL注入问题
得到的SQL语句:select * from tb_brand where id = 1
使用时机:
- 参数传递的时候:#{}
- 表名或者列名不固定的情况下:${} 会存在SQL注入问题
${} 可以用在jdbc不支持占位符的地方,比如:表名、排序等等。
@select("select * from tb_${tableName} where id=#{id}")
public Test findById(String tableName,int id);