Mybatis傳多個參數(三種解決方案)

最近隨着項目的深刻,逐漸的對數據庫的應用愈來愈深刻,已經開始根據自身的業務寫mapper方法了,而後看到這篇帖子,好的東西要吸取進來,原文以下:java

據我目前接觸到的傳多個參數的方案有三種。數據庫

第一種方案

DAO層的函數方法 app

Public User selectUser(String name,String area);

對應的Mapper.xml 函數

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

其中,#{0}表明接收的是dao層中的第一個參數,#{1}表明dao層中第二參數,更多參數一致日後加便可。spa

第二種方案

此方法採用Map傳多參數.code

Dao層的函數方法xml

Public User selectUser(Map paramMap);

對應的Mapper.xmlblog

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

Service層調用接口

Private User xxxSelectUser(){  
   Map paramMap=new hashMap();  
   paramMap.put(「userName」,」對應具體的參數值」);  
   paramMap.put(「userArea」,」對應具體的參數值」);  
   User user=xxx. selectUser(paramMap);}

我的認爲此方法不夠直觀,見到接口方法不能直接的知道要傳的參數是什麼。開發

第三種方案

Dao層的函數方法

Public User selectUser(@param(「userName」)String name,@param(「userArea」)String area);

對應的Mapper.xml

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

  

我的以爲這種方法比較好,能讓開發者看到dao層方法就知道該傳什麼樣的參數,比較直觀,我的推薦用此種方案。

-----------------------------------華麗原文分割線----------------------------------

ps:今天在網上看到第三種方案其實仍是傳個map進去,只不過不用像方案二同樣顯式的指定,而是經過param註解就能夠了

相關文章
相關標籤/搜索