【Mybatis】Mybatis传递多个参数
【Mybatis】Mybatis传递多个参数
在使用Mybatis过程中,经常会碰到传入多个参数的情形。
1. 多参数
基本的多参数传递方式:
xxxMapper.class
public List<XXXBean> getXXXBeanList(String param1, String parm2);
xxxMapper.xml
<select id="getXXXBeanList" resultType="XXBean">
  select t.* from tableName where id = #{0} and name = #{1}  
</select> 
注意点:
- 
 多参数不能使用parameterType 使用**#{index}**的方式,index从0开始,#{0}表示第一个参数,#{1}表示第二个参数,#{2}表示第三个参数,以此类推…
1.1 Map封装多参数
第一种“Map” ==》map
xxxMapper.class
public AdminRole isSameNameByRidAndName(@Param("map") Map<String,Object> map); 
xxxMapper.xml
<select id="isSameNameByRidAndName" parameterType="map" resultType="AdminRole">
    select id
    from admin_role
    where name = #{map.name} and  id <![CDATA[<>]]> #{map.rid}
</select> 
注意需要添加注解@Param(“map”),并且此时parameterType为map
第二种 “map” ==》 hashmap
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如何封装就不用了我说了吧。 
此时parameterType为hashmap,hashmap为Mybatis系统配置好的,直接进行使用即可
1.2 参数为List
public List<AdminRole> getAdminRoleListByRids(List<Integer> rids);
<select id="getAdminRoleListByRids" resultType="AdminRole">
    select id,name,name_zh,enabled
    from admin_role
    where id in
    <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
        #{item}
    </foreach>
</select> 
- 
 foreach 为Mybatis的动态sql中的其中一个用法 以上的sql效果为: select id,name,name_zh,enabled from admin_role where id in (1,2,3,4) 对于参数为List的参数,foreach的collection属性必须为list
1.3 注解处理多参数
通过使用注解@Param(“xxx”)进行指定参数
public int resetPassword(@Param("userName") String userName,@Param("password") String password,@Param("salt")String salt); 
<update id="resetPassword" parameterType="string">
    update User
    set password = #{password},salt = #{salt}
    where username = #{userName}
</update> 
- 
 在xml配置文件中,直接对应于@Param(“变量名”) 变量名进行使用即可

