来自:https://blog.csdn.net/cszhang5
最近碰到MyBatis传参的一些问题,经过一番探究,问题是解决了。
现对MyBatis传参进行下整理,权当做个笔记。
一、单个简单参数
-
public Item getItemById(String id); -
<select id="getItemById" parameterType="java.lang.String" resultType="resultMap"> -
SELECT t.c_id, t.c_name -
FROM titem t -
WHERE t.c_id = #{id,jdbcType=VARCHAR} -
</select>
二、多个简单参数
-
public List<Item> getItemList(String type, String color); -
<select id="getItemList" resultMap="resultMap"> -
SELECT t.c_id, t.c_name, t.c_type, t.c_color -
FROM titem -
WHERE t.c_type = #{0} -
AND t.c_color = #{1} -
</select>
不能使用parameterType,使用#{index}获取参数,索引从0开始
三、多参数注解传递
-
public List<Item> getItemList(@Param("type") String type, @Param("color") String color); -
<select id="getItemList" parameterType="java.lang.String" resultMap="resultMap"> -
SELECT t.c_id, t.c_name, t.c_type, t.c_color -
FROM titem -
WHERE t.c_type = #{type,jdbcType=VARCHAR} -
AND t.c_color = #{color,jdbcType=VARCHAR} -
</select>
四、Map封装多参数
-
public List<Item> getItemList(HashMap map); -
<select id="getItemListByMap" parameterType="hashmap" resultMap="resultMap"> -
SELECT t.c_id, t.c_name, t.c_type, t.c_color -
FROM titem -
WHERE t.c_type = #{type,jdbcType=VARCHAR} -
AND t.c_color = #{color,jdbcType=VARCHAR} -
</select>
hashmap为Mybatis配置,可直接使用。
五、List封装,in调用
-
public List<Item> getItemList(List<String> list); -
<select id="getItemList" resultMap="resultMap"> -
SELECT t.c_id, t.c_name, t.c_type, t.c_color -
FROM titem -
WHERE t.c_type in -
<foreach item="item" index="index" collection="list" open="(" separator="," close=")"> -
#{item} -
</foreach> -
</select>
六、List与String同时需要
-
List<String> type = new ArrayList<String>(); -
type.add("1"); -
type.add("2"); -
Map<String, Object> map = new HashMap<String, Object>(); -
map.put("list", list); -
map.put("color", "red"); -
public List<Item> getItemList(Map<String, Object> map){ -
return getSqlSession().selectList("getItemList", map); -
} -
<select id="getItemList" parameterType="java.util.Map" resultMap="resultMap"> -
SELECT t.c_id, t.c_name, t.c_type, t.c_color -
FROM titem -
WHERE t.c_color = #{color} -
AND t.c_type in -
<foreach collection="list" item="item" index="index" open="(" separator="," close=")"> -
#{item} -
</foreach> -
</select>
本文详细介绍了MyBatis框架中各种参数传递的方法,包括单个简单参数、多个简单参数、多参数注解传递、Map封装多参数、List封装以及List与String参数的结合使用。通过具体代码示例,深入探讨了不同场景下的参数处理技巧。

655

被折叠的 条评论
为什么被折叠?



