MyBatis傳參數四種方法

第一種方式:註解也是開發中最常見的一種方式(明顯看出自己所傳遞的參數,)

DAO類中的方法函數

 Public User selectUser(@param("userName")Stringname,@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>

  也可以是這樣

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

根據你所擁有的Mybatis版本而去 老版本需要添加參數類型

這種方法的好處在於比較直觀,只要看到dao方法就知道傳了什麼參數。


第二種方式:多個參數傳值(索引方式)(簡便,減少代碼量)

DAO類中的方法函數

 public List<XXXBean> getXXXBeanList(String xxId, String xxCode);  


對應Mapper.xml語句

 <select id="getXXXBeanList" resultType="XXBean">

    select t.* from tableName where id = #{0} and name = #{1}  

  </select>  

由於是多參數那麼就不能使用parameterType, 改用#{index}是第幾個就用第幾個的索引,索引從0開始



第三種方式:Map封裝多參數

 DAO類中的方法函數 
 public List<XXXBean> getXXXBeanList(HashMap map);  
對應Mapper.xml語句
<select id="getXXXBeanList" parameterType="hashmap" resultType="XXBean">     
     select 字段... from XXX where id=#{xxId} code = #{xxCode}    
    </select>   

Service層調用

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

其中hashmap是mybatis自己配置好的直接使用就行。map中key的名字是那個就在#{}使用那個,map如何封裝就不用了我說了吧。

第四種方式:List封裝in
 DAO類中的方法函數
public List<XXXBean> getXXXBeanList(List<String> list);  
對應的Mapper.xml文件
 <select id="getXXXBeanList" resultType="XXBean">
    select 字段... from XXX where id in
    <foreach item="item" index="index" collection="list" open="(" separator="," close=")">  
      #{item}  
    </foreach>  
  </select>  



foreach 最後的效果是select 字段... from XXX where id in ('1','2','3','4')







發佈了28 篇原創文章 · 獲贊 41 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章