参数替换
dao层的参数,是如何传入到xml中的sql语句的呢?
map传递
dao层接口参数为map,xml中可以直接通过map中的key,来绑定参数
假设传入的参数为两个,uname, password
public User selectUser(Map paramMap);
对应的xml为
<select id=" selectUser" resultMap="BaseResultMap">
select * from users where uname = #{uname,jdbcType=VARCHAR} and password=#{password,jdbcType=VARCHAR}
</select>
参数位置替换
这种是直接根据参数的索引位置来绑定, {0} 表示第一个参数, {1} 表示第二个参数
public User selectUser(String uname, String password);
对应的xml
<select id=" selectUser" resultMap="BaseResultMap">
select * from users where uname = #{0} and password=#{1}
</select>
注解指定方式
通过 @Param注解,直接指定name,在sql中即可通过name方式引用
public User selectUser(@Param("uname") String uname, @Param("password") String password);
对应的sql为
<select id=" selectUser" resultMap="BaseResultMap">
select * from users where uname = #{uname,jdbcType=VARCHAR} and password=#{password,jdbcType=VARCHAR}
</select>
$、#区别
使用#传入参数是,sql语句解析是会加上"",
比如 select * from table where name = #{name}
,传入的name为小李,那么最后打印出来的就是
select * from table where name = "小李"
,就是会当成字符串来解析
因此在动态排序时,比如 order by column
,这个时候务必要用${},因为如果你使用了#{}
区别
#
将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号$
将传入的数据直接显示生成在sql中#
方式能够很大程度防止sql注入$
方式无法防止Sql注入$
方式一般用于传入数据库对象,例如传入表名,列名
简单来说,两者区别: $ 是sql替换,直接拼成一条可执行sql; # 是参数替换