定义bean, 该bean中有一个集合属性emps
package com.atChina.bean;
import java.util.List;
public class Department {
private Integer id;
private List<Employee> emps;
public List<Employee> getEmps() {
return emps;
}
public void setEmps(List<Employee> emps) {
this.emps = emps;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
private Integer deptno;
private String dname;
private String loc;
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
@Override
public String toString() {
return "Department [id=" + id + ", emps=" + emps + ", deptno=" + deptno
+ ", dname=" + dname + ", loc=" + loc + "]";
}
}
sql映射文件,使用collection
<resultMap type="com.atChina.bean.Department" id="defineDept">
<id column="deptno" property="deptno"/>
<result column="dname" property="dname"/>
<result column="loc" property="loc"/>
<!--
collection:嵌套结果集的方式,定义关联集合类型的属性的封装规则
ofType: 指定集合里面元素的类型
-->
<collection property="emps" ofType="com.atChina.bean.Employee">
<!-- 定义这个集合元素的封装类型 -->
<id column="empno" property="empno" />
<result column="ename" property="ename" />
<result column="job" property="job" />
<result column="mgr" property="mgr" />
<result column="hiredate" property="hiredate" />
<result column="sal" property="sal" />
</collection>
</resultMap>
<select id="getDepartByDeptnoCol" resultMap="defineDept">
select a.empno, a.ename, a.job, a.mgr, a.hiredate, a.sal,
b.deptno, b.dname, b.loc
from depttest b, emptest a
where a.deptno = b.deptno
and b.deptno = #{deptno}
</select>