在mybatis的mapper xml文件中,可以使用两种方式#{parameterName}或者${parameterName}传递参数,前者死活预编译、效率高,而且可以防止sql注入问题。
使用#{parameterName}引用参数的时候,Mybatis会把这个参数认为是一个字符串,会对自动传入的数据加一个双引号。例如传入参数是“Smith”,那么在SQL(Select * from emp where name = #{employeeName})使用的时候就会转换为Select * from emp where name = 'Smith';
在使用${parameterName}引用参数的时候,Mybatis会把这个参数认为是常量。例如传入参数是“12”,在SQL(Select * from emp where age = ${employeeName})使用的时候就会转换为Select * from emp where age = 12,不会再数字上加引号,如果是#就会加引号变成字符串啦。
使用构成中的注意问题:
1、对于时间比较的查询中,使用#{}和${}时一定要注意格式,否则查询结果有问题。
select count(*) from test r where date_format(r.start_time,'%Y-%m-%d') <#{settleDate}
如果java中参数settleDate为字符串“2015-10-01”,这时生成的sql为(#{}会自动加上引号):
select count(*) from test r where date_format(r.start_time,'%Y-%m-%d') <'2015-10-01'
这样,查询的结果没有问题。或者直接使用
select count(*) from test r where r.start_time <#{settleDate}
生成的sql为:
<pre name="code" class="java">select count(*) from test r where r.start_time <'2015-10-01'
结果也是没有问题的。或者直接使用
<pre name="code" class="java" style="font-size: 14px;">select count(*) from test r where date_format(r.start_time,'%Y-%m-%d') <date_format(#{settleDate},'%Y-%m-%d')
此时,生成的sql为:
select count(*) from test r where date_format(r.start_time,'%Y-%m-%d') <date_format('2015-10-01','%Y-%m-%d')
而下面的查询结果是不对的:
</pre><p><span ></span></p><pre name="code" class="java" style="font-size:14px;">select count(*) from test r where date_format(r.start_time,'%Y-%m-%d') <${settleDate}
此时,生成的sql为:
select count(*) from test r where date_format(r.start_time,'%Y-%m-%d') <2015-10-01
这种方式也是错的,
select count(*) from test r where r.start_time <${settleDate}
此时,生成的sql为:
select count(*) from test r where r.start_time <2015-10-01
2、MyBatis排序时使用order by 动态参数时需要注意,用$而不是#