一、方法有多個參數
例如:
接口方法:
1
2
3
4
|
@Mapper public interface UserMapper { Integer insert( @Param ( "username" ) String username, @Param ( "address" ) String address); } |
對應的xml:
1
2
3
|
insert into user (username,address) values (#{username},#{address}); </insert> |
原因:當不使用 @Param 注解時,mybatis 是不認識哪個參數叫什么名字的,盡管在接口中定義了參數的名稱,mybatis仍然不認識。這時mybatis將會以接口中參數定義的順序和SQL語句中的表達式進行映射,這是默認的。
二、方法參數要取別名
例如
1
2
3
4
|
@Mapper public interface UserMapper { Integer insert( @Param ( "username" ) String username, @Param ( "address" ) String address); } |
對應的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
$ 會有注入的問題,但是有的時候不得不使用 $ 符號,例如要傳入列名或者表名的時候,這個時候必須要添加 @Param 注解
例如:
1
2
3
4
|
@Mapper public interface UserMapper { List<User> getAllUsers( @Param ( "order_by" )String order_by); } |
對應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 > |
四、動態 SQL 中使用了參數作為變量
如果在動態 SQL 中使用參數作為變量,那么也需要 @Param 注解,即使你只有一個參數。例如如下方法:
1
2
3
4
|
@Mapper public interface UserMapper { List<User> getUserById( @Param ( "id" )Integer id); } |
對應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 > |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/bear7/p/13572495.html