${}
:可以获取map中的值或者pojo对象属性的值;
${}
:取出的值直接拼装在sql语句中;会有安全问题;
<select id="getEmpByMap" resultType="com.atguigu.mybatis.bean.Employee">
select * from ${tableName} where id=${id} and last_name=#{lastName}
</select>
SQL语句是这样的(id=2
):
Preparing: select * from tbl_employee where id=2 and last_name=?
在原生jdbc
不支持占位符的地方我们就可以使用${}
进行取值
比如:
分表:select * from ${year}_salary where xxx;
按照年份分表拆分
排序:select * from tbl_employee order by ${f_name} ${order}
大多情况下,我们去参数的值都应该去使用#{}
#{}
:可以获取map中的值或者pojo对象属性的值,只能取出参数位置的值;
select * from #{tableName} where id=${id} and last_name=#{lastName}
向上面的#{tableName}
是取不到的,因为它不是参数位置的值
#{}
:是以预编译的形式,将参数设置到sql
语句中;PreparedStatement
;防止sql
注入
<select id="getEmpByMap" resultType="com.atguigu.mybatis.bean.Employee">
select * from tbl_employee where id=#{id} and last_name=#{lastName}
</select>
SQL语句是这样的(id=?
):
Preparing: select * from tbl_employee where id=? and last_name=?
#{}
:更丰富的用法:
参数也可以指定一个特殊的数据类型:
参数位置支持的属性有以下那么多种:
javaType、 jdbcType、 mode(存储过程)、 numericScale、
resultMap、 typeHandler、 jdbcTypeName、 expression(未来准备支持的功能);
jdbcType
通常需要在某种特定的条件下被设置:
在我们数据为null
的时候,有些数据库可能不能识别mybatis
对null
的默认处理。比如Oracle
(报错);
比如:
Employee employee = new Employee(null, "jerry4",null, "1");
mapper.addEmp(employee);
System.out.println(employee.getId());
报错:JdbcType OTHER
:无效的类型;因为mybatis
对所有的null
都映射的是原生Jdbc
的OTHER
类型,oracle
不能正确处理;
由于全局配置中:jdbcTypeForNull=OTHER
;oracle
不支持;两种办法
1、insert into employees(EMPLOYEE_ID,LAST_NAME,EMAIL)
values(#{id},#{lastName},#{email,jdbcType=NULL})
2、在全局配置文件(mybatis-config.xml
)的<settings>
标签中设置jdbcTypeForNull=NULL
:
<settings>
<setting name="jdbcTypeForNull" value="NULL"/>
</settings>