实际上在mybatis中:两种取值方式:
- #{属性名}:是参数预编译的方式,参数的位置都是用?替代,参数后来都是预编译设置进去的;安全,不会有sql注入问题
id=#{id} and empname=#{empName}:
select * from t_employee where id=? and empname=?
- ${属性名}:不是参数预编译,而是直接和sql语句进行拼串;不安全;
例如
id=${id} and empname=#{empName}:
select * from t_employee where id=1 and empname=?
//若在id处传入一个'1 or 1=1 or';
select * from t_employee where id= 1 or 1=1 or and empname=?
这样子的话1 = 1 恒成立,就可以遍历表中所有数据
当然,${}并不是就没有使用场景了,例如:在处理日志表的时候,数据过大可能会采取分表的形式:log_2017_12、log_2018_1;
因此在查询某张表的时候,由于表名参数是不支持预编译的,即不能使用#{表名的key},在这个时候就需要使用${}了
public void test01() throws IOException {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
EmployeeDao mapper = sqlSession.getMapper(EmployeeDao.class);
HashMap<String, Object> map = new HashMap<>();
map.put("id", "1");
map.put("empName", "admin");
map.put("tableName", "t_employee");
Employee empByIdAndEmpName2 = mapper.getEmpByIdAndEmpName2(map);
System.out.println("eempByIdAndEmpName2-->"+empByIdAndEmpName2);
} finally {
sqlSession.close();
}
}
<mapper namespace="com.czl.dao.EmployeeDao">
<select id="getEmpByIdAndEmpName2" resultType="com.czl.bean.Employee">
select * from ${tableName} where id=#{id} and empname=#{empName}
</select>
</mapper>
一般都是使用#{};安全;在不支持参数预编译的位置要进行取值就使用${};
135

被折叠的 条评论
为什么被折叠?



