此章对 Dao 接口中 多个基础类型参数、或单参数但为 Bean / Map 等复杂类型、或者多个复杂类型参数 的情况
- _parameter
当 Dao 接口中定义的是一个复杂类型参数时,此时内置参数 _parameter 代表的是当前参数对应的复杂类型对象
当 Dao 接口中定义的是多个参数时,多个参数会被封装为一个 map 类型,此时内置参数 _parameter 代表的是封装了多个参数的 Map 对象
简而言之:接口定义为单参数,则 _parameter 为当前参数,接口定义为多参数,则 _parameter 为参数集的 Map 对象
- 参数的说明
当单个基本参数时,未别名时,取值随意命名,判断必须 _parameter,如果通过 @Param 指定了命名,只能使用 命名;
当单个复杂参数时,未别名时,属性取值和属性判断都是直接使用属性名称(若Map类型使用Key名称),别名之后,都必须携带别名的前缀,即别名.属性
当多个基本参数时,属性的默认取值和判断都为 arg[index],别名之后直接使用 别名
当多个复杂参数时,属性的默认取值和判断都为 arg[index].属性名称,别名后通过 别名.属性
当多个任何参数时,可以在 Service 层封装为一个 Map 对象,然后以单参数的形式传递给 Dao 层
总而言之:单参数基础类型,直接通过 _parameter/随意命名 引用;单参数的复杂类型/自定实体,直接通过 属性名称 引用,Map 通过 key 引用;单参数别名、单参数Array/List、无论别名与否和参数类型的多参数,都将封装为 Map 对象,以别名(未别名以序号)获取参数,要获取参数的属性时再通过 别名.属性名称 获取
一、顺序(索引)传参
在 XML 中,通过 #{arg+index}确定参数,索引从 0 开始;不使用 parameterType 属性 或 指定为 Map 类型
public interface StudentDao {
public Student selectStudent(String name, Integer clsId);
}
<select id="selectStudent" resultType="com.xl.entity.Student">
<!-- 以 MyBatis 3.4.6 的测试来看是 arg+Index 非 index -->
SELECT * FROM student WHERE stu_name = #{arg0} AND cls_id = #{arg1}
</select>
二、@Param 注解传参
在 DAO 中直接通过 @Param 指定参数的名称,在 XML 中使用此名称;不使用 parameterType 属性 或 指定为 Map 类型
public interface StudentDao {
public Student selectStudent(@Param("stuName") String name, @Param("clsId") Integer clsId);
}
<select id="selectStudent" resultType="com.xl.entity.Student">
SELECT * FROM student WHERE stu_name = #{stuName} AND cls_id = #{clsId}
</select>
三、Java Map 传参
在 XML 中,使用 #{key} 指定 Map 里面的 key 名称,使用 parameterType 指定为 Map 类型 或 不指定
public interface StudentDao {
/**
* Service:
* Map<String,Object> map = new HashMap<>();
* map.put("stuName", "zhangwu");
* map.put("clsId", "1001");
*/
public Student selectStudent(Map<String, Object> map);
}
<select id="selectStudent" parameterType="java.util.Map" resultType="com.xl.entity.Student">
SELECT * FROM student WHERE stu_name = #{stuName} AND cls_id = #{clsId}
</select>
四、Java Bean 传参
在 XML 中,使用 #{attr} 对应 Bean 里面的成员属性,使用 parameterType 指定为 Bean 类型 或 不指定
public interface StudentDao {
/**
* Service:
* Student stu = new Student();
* stu.setName("zhangwu");
* stu.setClsId(1001);
*/
public Student selectStudent(Student student);
}
<select id="selectStudent" parameterType="com.xl.entity.Student" resultType="com.xl.entity.Student">
SELECT * FROM student WHERE stu_name = #{name} AND cls_id = #{clsId}
</select>
五、多个 Bean 传参
- 1、索引参数
public interface StudentDao {
public Student selectStudent(Student student, Page page);
}
<select id="selectStudent" resultType="com.xl.entity.Student">
SELECT * FROM student WHERE stu_name = #{arg0.name} AND cls_id = #{arg0.clsId} limit ${arg1.pageNum}, ${arg1.pageSize}
</select>
- 2、别名参数
public interface StudentDao {
public Student selectStudent(@Param("stu") Student student, @Param("page") Page page);
}
<select id="selectStudent" resultType="com.xl.entity.Student">
SELECT * FROM student WHERE stu_name = #{stu.name} AND cls_id = #{stu.clsId} limit ${page.pageNum}, ${page.pageSize}
</select>