一、方法有多個(gè)參數(shù)
例如:
接口方法:
1
2
3
4
|
@Mapper public interface UserMapper { Integer insert( @Param ( "username" ) String username, @Param ( "address" ) String address); } |
對應(yīng)的xml:
1
2
3
|
insert into user (username,address) values (#{username},#{address}); </insert> |
原因:當(dāng)不使用 @Param 注解時(shí),mybatis 是不認(rèn)識哪個(gè)參數(shù)叫什么名字的,盡管在接口中定義了參數(shù)的名稱,mybatis仍然不認(rèn)識。這時(shí)mybatis將會以接口中參數(shù)定義的順序和SQL語句中的表達(dá)式進(jìn)行映射,這是默認(rèn)的。
二、方法參數(shù)要取別名
例如
1
2
3
4
|
@Mapper public interface UserMapper { Integer insert( @Param ( "username" ) String username, @Param ( "address" ) String address); } |
對應(yīng)的xml:
1
2
3
|
< insert id = "insert" parameterType = "org.javaboy.helloboot.bean.User" > insert into user (username,address) values (#{username},#{address}); </ insert > |
三、XML 中的 SQL 使用了 $ 拼接sql
$ 會有注入的問題,但是有的時(shí)候不得不使用 $ 符號,例如要傳入列名或者表名的時(shí)候,這個(gè)時(shí)候必須要添加 @Param 注解
例如:
1
2
3
4
|
@Mapper public interface UserMapper { List<User> getAllUsers( @Param ( "order_by" )String order_by); } |
對應(yīng)xml:
1
2
3
4
5
6
|
< select id = "getAllUsers" resultType = "org.javaboy.helloboot.bean.User" > select * from user < if test = "order_by!=null and order_by!=''" > order by ${order_by} desc </ if > </ select > |
四、動態(tài) SQL 中使用了參數(shù)作為變量
如果在動態(tài) SQL 中使用參數(shù)作為變量,那么也需要 @Param 注解,即使你只有一個(gè)參數(shù)。例如如下方法:
1
2
3
4
|
@Mapper public interface UserMapper { List<User> getUserById( @Param ( "id" )Integer id); } |
對應(yīng)xml:
1
2
3
4
5
6
|
< select id = "getUserById" resultType = "org.javaboy.helloboot.bean.User" > select * from user < if test = "id!=null" > where id=#{id} </ if > </ select > |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/bear7/p/13572495.html