MyBatis-parameterType 取出入参值

时间:2021-08-06 20:07:54

SQL 映射文件的几种入参情况

一、单个基本类型参数

public MyUser selectMyUser(Integer id);
<!-- #{参数名或任意名}:取出参数值 -->
<select id="selectMyUser" resultType="myUser" parameterType="integer">
select * from myuser where id = #{id}
</select>

二、多个基本类型参数

多个参数会被封装成 一个Map,Key 为 param1...paramN,或者参数的索引 (0开始):arg0...argN,Value 为传入的参数值

public MyUser selectMyUserIdAndAge(Integer id,Integer age);
<!-- #{arg0}/#{param1}:取出参数值 -->
<select id="selectMyUserIdAndAge" resultType="myUser">
select * from myuser where id = #{param1} and age = #{arg1}
</select>

使用 @Param 注解

public MyUser selectMyUserIdAndAge(@Param("id") Integer id, @Param("age") Integer age);
<!-- #{@Param标识值}:取出参数值 -->
<select id="selectMyUserIdAndAge" resultType="myUser">
select * from myuser where id = #{id} and age = #{age}
</select>

封装成 Map 对象

public MyUser selectMyUserIdAndAgeOfMap(Map<String,Object> map);
<!-- #{key}:取出map中对应的值 -->
<select id="selectMyUserIdAndAgeOfMap" resultType="myUser">
select * from myuser where id = #{id} and age = #{age}
</select>

封装成一个类,例直接使用 POJO 对象

public Integer updateMyUser(MyUser user);
<!-- #{属性名}:取出传入pojo的属性值 -->
<update id="updateMyUser" parameterType="myUser">
update myuser set name=#{name},age=#{age} where id=#{id}
</update>

三、Collection 集合类型

public MyUser selectMyUserByList(List<Integer> ids);
<!-- #{collection[0]}:取出参数值,若为 List 还可使用 #{list[0]} -->
<select id="selectMyUserByList" resultType="myUser">
select * from myuser where id = #{list[0]}
</select>

四、Array 数组类型

public MyUser selectMyUserByArray(Integer[] integers);
<!-- #{array[0]}:取出参数值 -->
<select id="selectMyUserByArray" resultType="myUser">
select * from myuser where id = #{array[0]}
</select>

五、多种参数类型

public MyUser selectMyUserIdAndAge(Integer id, @Param("user") MyUser user);
<select id="selectMyUserIdAndAge" resultType="myUser">
select * from myuser where id = #{arg0} and age = #{user.age}
</select>

附上 MyBatis 封装集合的方法

org.apache.ibatis.session.defaults.DefaultSqlSession

public class DefaultSqlSession implements SqlSession {

    private Object wrapCollection(final Object object) {
if (object instanceof Collection) {
StrictMap<Object> map = new StrictMap<>();
map.put("collection", object);
if (object instanceof List) {
map.put("list", object);
}
return map;
} else if (object != null && object.getClass().isArray()) {
StrictMap<Object> map = new StrictMap<>();
map.put("array", object);
return map;
}
return object;
}

如果传入的是 Collection(List、Set)集合类型或者是 Array 数组类型,会把传入的 Collection 集合或者 Array 数组封装在 Map 中。