1. 程式人生 > >Mybatis中#{}和${}輸入引數的區別

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}