mybatis使用#{}时, 是会自动在将该变量加上引号,例如:
select * from user where name = #{name};
-- 解析为
select * from user where name = ?;
执行SQL时,MyBatis会将#{name}使用占位符(?)替代,然后调用preparedStatement进行预编译,最终执行的sql语句为:
select * from user where name = 'xiao';
mybatis使用${}时, 是直接将对象的值与${}进行替换,例如:
select * from ${name}
-- 执行的sql语句
select * from user
总结:就是当我们需要拼接的变量上是列名这些不能带单引号时,就必须使用${}。
常见的使用${}的情况:
1.当sql中表名是从参数中取的情况
2.order by排序语句中,因为order by 后边必须跟字段名,这个字段名不能带引号,如果带引号会被识别会字符串,而不是字段。