- #{}:可以获取map中的值或者pojo对象属性的值
- ${}:可以获取map中的值或者pojo对象属性的值
- 区别:
- #{}:是以预编译的形式,将参数设置到sql语句中,相当于原生jdbc的PreparedStatement;防止sql注入
- ${}:取出的值直接拼接在sql语句中;会有安全问题;
- 大多情况下,我们取参数的值都应该去使用#{};
- 区别:
DEBUG 01-23 09:00:50,805 ==> Preparing: select * from tb1_employee where id = 1 and last_name = ? (BaseJdbcLogger.java:159)
DEBUG 01-23 09:00:50,835 ==> Parameters: Tom(String) (BaseJdbcLogger.java:159)
DEBUG 01-23 09:00:50,852 <== Total: 0 (BaseJdbcLogger.java:159)
原生jdbc不支持占位符的地方,我们就可以使用${}进行取值
比如分表:按照年份分表拆分,排序等
select * from 2017_salary where xxx;
写成:
select * from ${year}_salary where xxx;
select * from tb1_employee order by ${f_name} ${order}
- example
<!--public Employee getEmpByMap(Map<String,Object> map);--><select id="getEmpByMap" resultType="com.atguigu.mybatis.bean.Employee">select * from ${tableName} where id = #{id} and last_name = #{lastName}</select>
@Testpublic void test03() throws IOException {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();SqlSession sqlSession = sqlSessionFactory.openSession();try{EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);Map<String,Object> map = new HashMap<>();map.put("id",1);map.put("lastName","Tom");map.put("tableName","tb1_employee");Employee employee = mapper.getEmpByMap(map);System.out.println(employee);}finally {sqlSession.close();}}