mapper 傳多個參數


Mybatis的Mapper接口的參數,一般是一個對象,但如果不是對象,並且有多個參數的時候呢?我們第一個的想法是把參數封裝成一個java.util.Map類型,然后在方法的注釋上面寫上map的key是什么,但是,這樣的做法明顯不夠直觀,不能夠一眼看出這個方法的參數是什么,並且,影響到了java方法的多態性(方法名相同,參數數量或類型不同)。下面的方法一和方法二能夠解決問題!

DAO層的函數方法 

 
1
Public User selectUser(String name ,String area);

對應的Mapper.xml  

 
1
2
3
< select id= "selectUser" resultMap= "BaseResultMap" >
     select  from user_user_t   where user_name = #{0} and user_area=#{1}
</ select >

其中,#{0}代表接收的是dao層中的第一個參數,#{1}代表dao層中第二參數,更多參數一致往后加即可。

此方法采用Map傳多參數.

Dao層的函數方法

 
1
Public User selectUser(Map paramMap);

對應的Mapper.xml

 
1
2
3
< select id= " selectUser" resultMap= "BaseResultMap" >
    select  from user_user_t   where user_name = #{userName,jdbcType= VARCHAR } and user_area=#{userArea,jdbcType= VARCHAR }
</ select >

Service層調用

 
1
2
3
4
5
Private User xxxSelectUser(){
Map paramMap=new hashMap();
paramMap.put(“userName”,”對應具體的參數值”);
paramMap.put(“userArea”,”對應具體的參數值”);
User user =xxx. selectUser(paramMap);}

個人認為此方法不夠直觀,見到接口方法不能直接的知道要傳的參數是什么。

Dao層的函數方法

 
1
Public User selectUser(@Param(“userName”)String name,@Param(“userArea”)String area);

對應的Mapper.xml

 
1
2
3
< select id= " selectUser" resultMap= "BaseResultMap" >
    select  from user_user_t   where user_name = #{userName,jdbcType= VARCHAR } and user_area=#{userArea,jdbcType= VARCHAR }
</ select

個人覺得這種方法比較好,能讓開發者看到dao層方法就知道該傳什么樣的參數,比較直觀,個人推薦用此種方案


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM