Mybatis中#{}和${}输入参数的区别

#{}

mybatis 会进行预编译,比如(假设ID=6):

select * from user where id=#{ID}

会先编译成

select * from user where id=?

然后用ID的值(6)替代?

#{}的优势

更安全

如果传入的值值中有#(#在sql中表示注释)使用#{},不会使#后面的sql失效,当传入的name参数中有#,比如hh#:

select * from user where name=#{name} and id=#{ID}

执行的sql为

select * from user where name="hh#" and id=6

如果用${}

select * from user where name=${name} and id=${ID}

则执行的sql为

select * from user where name="hh" # and id=6

因为#表示注释所以执行效果相当于

select * from user where name="hh"

可以指定其它属性

如果name参数传入的值为null,mybatis会默认name值为other类型 ,但是oracle数据库不能处理other类型,因此会报不能识别的错误。此时就可以用jdbcType属性指定类型

select * from user where name=#{name, jdbcType=null} and id=${ID}

当然也可以在mybatis配置文件中进行配置

<settings>
        <setting name="jdbcTypeForNull" value="NULL"/>
    </settings>

${}

mybatis 会直接进行编译,比如(假设ID=6):

select * from user where id=${ID}

会直接编译成

select * from user where id=6

${}的优势

jdbc不支持占位符的地方可以使用${}进行取值,比如表名和排序字段

select * from ${user} where name=#{name} and id=#{ID} order by ${name}

猜你喜欢

转载自blog.csdn.net/DingKG/article/details/82804863
今日推荐