Mybatis (ParameterType) 如何傳遞多個不同類型的參數

偶然碰到一個需要給xml傳一個String類型和一個Integer類型的需求,當時心想用map感覺有點太浪費,所以專門研究了下各種方式。

方法一:不需要寫parameterType參數

 

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開始

方法二:基於註解(最簡單)

 

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封裝

 

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> 

總結

傳遞list和map在資源消耗上肯定遠大於方法一和方法二,但是有一些特殊的情形需要傳遞list,比如你需要傳遞一個id集合並批量對id進行sql操作然後再返回等等。所以都需要了解。



作者:FantJ
鏈接:https://www.jianshu.com/p/d977eaadd1ed
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章