Java MyBatis3(7)参数取值

序言

在mybatis中,参数取值方式有两种:#{ } 和 ${ }

一、#{ }

select * from student where name=#{name}

编译后执行的sql语句:

select * from student where name=?

说明:

 #{ }实现的是JDBC 中preparedStatement中的占位符。

#{ }适合sql语句中的参数传值,构建sql语句#{ }是不可以的。

select * from #{tablename} ;

编译后的sql语句为:

select * from ?

这在sql中是不允许的,所以要用${ 拼接}

#{ }试用的场景

1.where语句里的判断:

a=#{a},a>#{a},a in {#{a}},a like #{a}........

2.set语句:

set a=#{a}

3.插入语句中:

values(#{a},.......)

4.其他大部分适合${ }进行拼接

二、${ }

select * from student where name=${name}

编译后执行的sql语句:

select * from student where name=name

说明:

${ }取参方式是简单的字符串拼接,不适合进行参数传值,不然会有sql语句注入的危险。

它更加适合的是构建sql语句。

资料

原文地址:https://www.cnblogs.com/cnki/p/9346313.html