天天看點

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操作然後再傳回等等。是以都需要了解。