Mybatis_SQL映射文件_mybtis的两种取值

实际上在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>

一般都是使用#{};安全;在不支持参数预编译的位置要进行取值就使用${};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值