偶然碰到一個需要給xml傳一個String類型和一個Integer類型的需求置逻,當(dāng)時心想用map感覺有點太浪費推沸,所以專門研究了下各種方式。
方法一:不需要寫parameterType參數(shù)
public List<XXXBean> getXXXBeanList(String xxId, String xxCode);
<select id="getXXXBeanList" resultType="XXBean">
select t.* from tableName where id = #{0} and name = #{1}
</select>
由于是多參數(shù)那么就不能使用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>
由于是多參數(shù)那么就不能使用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>
總結(jié)
傳遞list和map在資源消耗上肯定遠大于方法一和方法二猴伶,但是有一些特殊的情形需要傳遞list课舍,比如你需要傳遞一個id集合并批量對id進行sql操作然后再返回等等。所以都需要了解他挎。