mybatis傳入多個參數


mybatis傳入多個參數

 

寫在開頭:

需要查閱本文的基本都是需要傳入多個參數的,這里記住一句話:無論你傳的參數是什么樣的,最后mybtis都會將你傳入的轉換為map的,那么既然這樣,當我們要傳入多個參數時,何不直接給與map類型即可,然后mapper.xml通過#{map.key}來獲取值即可,這個特別適合動態搜索,或者多個參數的查詢,並且可以在mapper的xml語句中通過if判斷來實現若為空,則不添加查詢條件,

<if test="userId != null">
#{userId,jdbcType=VARCHAR},
</if>

還可以通過for來進行遍歷。

一、單個參數:

public List<XXBean> getXXBeanList(@param("id")String id); <select id="getXXXBeanList" parameterType="java.lang.String" resultType="XXBean">   select t.* from tableName t where t.id= #{id} </select> 其中方法名和ID一致,#{}中的參數名與方法中的參數名一致, 這里采用的是@Param這個參數,實際上@Param這個最后會被Mabatis封裝為map類型的。 select 后的字段列表要和bean中的屬性名一致, 如果不一致的可以用 as 來補充。

二、多參數:

方案1

public List<XXXBean> getXXXBeanList(String xxId, String xxCode); <select id="getXXXBeanList" resultType="XXBean">   select t.* from tableName where id = #{0} and name = #{1} </select> 由於是多參數那么就不能使用parameterType, 改用#{index}是第幾個就用第幾個的索引,索引從0開始

方案2(推薦)基於注解

public List<XXXBean> getXXXBeanList(@Param("id")String id, @Param("code")String code); <select id="getXXXBeanList" resultType="XXBean">   select t.* from tableName where id = #{id} and name = #{code} </select> 由於是多參數那么就不能使用parameterType, 這里用@Param來指定哪一個

三、Map封裝多參數:  

public List<XXXBean> getXXXBeanList(HashMap map); <select id="getXXXBeanList" parameterType="hashmap" resultType="XXBean">   select 字段... from XXX where id=#{xxId} code = #{xxCode} </select> 其中hashmap是mybatis自己配置好的直接使用就行。map中key的名字是那個就在#{}使用那個,map如何封裝就不用了我說了吧。 

 四、List封裝in:

public List<XXXBean> getXXXBeanList(List<String> list); <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') 

五、selectList()只能傳遞一個參數,但實際所需參數既要包含String類型,又要包含List類型時的處理方法:

將參數放入Map,再取出Map中的List遍歷。如下:

List<String> list_3 = new ArrayList<String>(); Map<String, Object> map2 = new HashMap<String, Object>(); list.add("1"); 
list.add("2");
map.put("list", list); //網址id map.put("siteTag", "0");//網址類型
public List<SysWeb> getSysInfo(Map<String, Object> map2) {   return getSqlSession().selectList("sysweb.getSysInfo", map2); }
<select id="getSysInfo" parameterType="java.util.Map" resultType="SysWeb">   select t.sysSiteId, t.siteName, t1.mzNum as siteTagNum, t1.mzName as siteTag, t.url, t.iconPath  from TD_WEB_SYSSITE t  left join TD_MZ_MZDY t1 on t1.mzNum = t.siteTag and t1.mzType = 10  WHERE t.siteTag = #{siteTag }  and t.sysSiteId not in  <foreach collection="list" item="item" index="index" open="(" close=")" separator=",">   #{item}  </foreach> </select>


免責聲明!

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



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