Mybatis中的collection标签中的javaType和ofType属性的区别

Mybatis中的collection标签中的javaType和ofType属性的区别

在使用mybatis时,有时候需要在数据库中进行关联查询(left/right join)来根据某个字段获取到另一个表的的一个List集合。在配置resultMap时,需要用到collection标签对这个LIst属性进行映射:
比如在部门表中有一个列表List存放这个表中的所有员工,javaBean如下:

public class Department {

	private Integer id;
	private String departmentName;
	private List<Employee> emps;
}

员工表如下:

public class Employee {

	private Integer id;
	private String lastName;
	private String email;
	private String gender;
}

用mybatis对这两个表进行关联查询查询:

<select id="getDeptByIdPlus" resultMap="MyDept">
		SELECT d.id did, d.dept_name dept_name,
			e.id eid, e.last_name last_name, e.email email,e.gender gender
		FROM department d
		LEFT JOIN employee e
		ON d.id = e.d_id
		WHERE d.id = 1
</select> 

由于是通过关联查询得到的这个List,所以此时需要用到resultMap标签对返回值的类型进行自定义:

<resultMap type="bean.Department" id="MyDept">
		<id column="did" property="id"/>
		<result column="dept_name" property="departmentName"/>
		<!-- 
			collection定义关联的集合类型的属性的封装规则:
			property="emps":指定这是哪个集合属性,这里为那个集合属性emps
			ofType:指定集合内封装的JavaBean类型(集合内装的什么),这里即为Employee类
		 -->
		<collection property="emps" ofType="bean.Employee">
			<!-- 定义集合中元素的封装规则 -->
			<id column="eid" property="id"/>
			<result column="last_name" property="lastName"/>
			<result column="email" property="email"/>
			<result column="gender" property="gender"/>
		</collection>
</resultMap>

在这个resultMap 标签中,用collection这个子标签对这个List进行映射。通过Alt+/可以发现,collection标签中包含两个关于javaBean的Type属性分别是ofType和javaType。其中ofType指定的这个List所存放的javaBean的类型,比如这里就是Employee类型。而javaType指定的当前这个配置的标签所对应的属性,比如我们这里的collection配置的是一个List,就可以配置成javaType=“java.util.ArrayList”(此处没写)。

猜你喜欢

转载自blog.csdn.net/sinat_38848255/article/details/107622008