mybatis入参处理

mybatis入参处理

八月 19, 2019

参数处理详解

单参数Mybatis不做任何处理,直接取出参数赋值给xml文件如:#{id}

多参数:

默认情况下会对参数按照顺序赋给参数#{param1},#{param2},#{arg1},#{arg2},

1)JavaBean传递参数

将参数封装成一个实体类
1
public Person getPersonByNameAndGender(Person person);

2)Map接口

如果参数个数比较少,而且没有对应的JavaBean,可以封装成Map
XML文件中:#{key} 取出map中对应的值
1
public Person getPersonByNameAndGender(Map<String,Object> param);
1
2
3
4
Map<String,Object> param=new HashMap<String, Object>();
param.put("name","wangwu");
param.put("gender","f");*/
Person person=personMapper.getPersonByNameAndGender(param);
1
select *from person where username=#{name} ang gender=#{gender}

3)注解@param

通过注解明确的指定封装参数时的map和key
1
public Person getPersonByNameAndGender(@Param("username") String username, String gender)*

参数为Collection,List,Array会封装为Map,但有一定的规则(collection接口包含list和set接口)(@param也同样适用,注解的value替代collection或map)

当参数类型为Collection接口时,转化为map。map的key为collection

1
public Person getPersonByCollection(Collection list);
1
select *from person where id=#{collection[0]}

参数类型为List接口时,除collection的值外,list作为key(因为版本的问题)

当参数类型为数组时,转化为map。map的key为array

1
public List<Person> getPersonsByIds(int[] ids)
1
select *from person where id=#{array[0]}