Mybatis的mapper文件$和#的区别

1.区别

${key},mapper在做解析的时候会直接在sql上拼接key的值

#{key},mapper在做解析的时候如果key类型是字符串,key的值加单引号,如果为数字类型,直接拼key的值。

2.常见情况

#{key},常用来传参,${key}可以用来拼接sql。

3.使用示例

#{key}

select * from user_table where user_id = #{userId} and user_name = #{username}

如果参数userId的值为:1,username的值为: 张三。最终sql为

select * from user_table where user_id = 1 and user_name = '张三'

${key}

如果想将sql语句作为参数,key的值为 LEFT JOIN order_table ON order_table.user_id = user_table.user_id,userId的值为:1

最终sql。

select user_table.* from user_table ${key} where user_table.user_id = #{userId}

SELECT user_table.* FROM user_table LEFT JOIN order_table ON order_table.user_id = user_table.user_id WHERE user_id = 1

4.总结

${}用来拼接一些通过代码生成的sql。${}也可以用来接收参数,但是不建议使用。

#{}用来接收参数,还可以用来防止sql注入

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容