MyBatis 传入多个参数方法

一、单参数:

public List<XXBean> getXXBeanList(String xxCode);  
<select id="getXXXBeanList" parameterType="java.lang.String" resultType="XXBean">   select t.* from tableName t where t.xxCode= #{id}
</select> 其中方法名和 select的id一致,#{}中的参数名与方法中的参数名一致。select 后的字段列表要和bean中的属性名一致, 如果不一致的可以用 as 来补充。


二、多参数(索引方式):

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


三、多参数(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的名字是哪个就在#{}使用哪个。

四、多参数(注解方式):

public AddrInfo getAddrInfo(@Param("corpId")int corpId, @Param("addrId")int addrId);
 
<select id="getAddrInfo"  resultMap="com.xxx.xxx.AddrInfo">
       SELECT * FROM addrinfo 
    where addr_id=#{addrId} and corp_id=#{corpId}
</select> 以前在<select>语句中要带parameterType的,现在可以不要这样写。

五、多参数(Javabean)

扩展:

1、List封装in:

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>  

foreach 最后的效果是select 字段... from XXX where id in ('1','2','3','4') 

2、参数是数组,使用 array 获得参数,再用foreach循环。


3、参数是List,使用 list 或 collection 获得参数,再用foreach循环。


4、参数是Set,使用 collection 获得参数,再用foreach循环。

5、参数既包含String类型又包含List类型(Map封装):

将参数放入Map,再取出Map中的List遍历。如下:

List<String> list = new ArrayList<String>();
list.add("1"); list.add("2"); Map<String, Object> map = new HashMap<String, Object>(); map.put("list", list); map.put("siteTag", "0");

public List<SysWeb> getSysInfo(Map<String, Object> map);

<select id="getSysInfo" parameterType="java.util.Map" resultType="SysWeb">
  select * from tableName
   where siteTag = #{siteTag} 
   and sysSiteId in 
   <foreach collection="list" item="item" index="index" open="(" close=")" separator=",">
       #{item}
   </foreach>
 </select>

6、同时传入对象参数和字符串参数

mapper.java
        字符串和对象参数都用@param注解:
import org.apache.ibatis.annotations.Param;
public List<User> selectAllUsers(@Param("user") User user, @Param("bm") String bm);
 mapper.xml
使用 #{对象名.属性名} 取值,如 #{user.id} ,动态SQL判断时也要用 对象名.属性名
<select id="selectAllUsers" resultMap="UserMap">
select * from user where bm = #{bm}
<if test="user.name != null and user.name != ''"> and name like concat('%', #{user.name}, '%')</if>
<if test="user.sex != null"> and sex = #{user.sex}</if>
</select>

        注意,使用了 @pram 注解的话在 mapper.xml 不加 parameterType。