1、首先准备两个表:
dept部门表、employee员工表。他们的关系为一个部门下有多个员工
dept表:
employee表:
2、编写实体类:
关联查询就不能用与单表映射的实体类了,我们编写一个一对多的实体类。
该类继承dept类,然后用list集合保存一个部门下的多个员工信息。
package com.asiainfo.demo.myEntity;
import com.asiainfo.demo.entity.Dept;
import com.asiainfo.demo.entity.Employee;
import java.util.List;
/**
* @author:tongys
* @createTime:2020/6/11 19:24
*/
public class DeptWithEmployee extends Dept { //自定义一个“一对多”的实体类,一个部门下有多个员工
private List<Employee> employeeList;
public List<Employee> getEmployeeList(){
return employeeList;
}
public void setEmployeeList(List<Employee> list){
employeeList = list;
}
}
3、编写mapper.xml映射文件
找到dept表的xml映射文件,在该文件中我们需要自定义一个结果集来接收查询返回的数据。
<!-- 自定义“一对多”的结果集 -->
<resultMap id="deptAndEmployee" type="com.asiainfo.demo.myEntity.DeptWithEmployee">
<result column="dept_name" property="deptName" jdbcType="VARCHAR"/>
<!-- 用collection来声明结果集中的集合 -->
<!-- 注意使用ofType来声明集合中的数据类型 -->
<collection property="employeeList" ofType="com.asiainfo.demo.entity.Employee">
<result column="name" property="name" jdbcType="VARCHAR"/>
</collection>
</resultMap>
然后编写sql语句,注意代码注释中的说明!
<!-- 以下为自定义sql -->
<!-- 结果集要使用我们在上边自定义的那个 -->
<select id="queryDeptAndEmployee" resultMap="deptAndEmployee">
SELECT b.dept_name,a.name from employee a ,dept b where a.dept = b.id;
</select>
4、在mapper.java类中声明方法,并进行测试
package com.asiainfo.demo.controller;
import com.asiainfo.demo.myEntity.DeptWithEmployee;
import com.asiainfo.demo.service.DeptService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
/**
* @author:tongys
* @createTime:2020/4/9 13:27
*/
@Controller
public class TestController {
@Resource
private DeptService deptService;
/**
* 测试一对多(一个部门对应多个员工)的xml配置与查询
* @return
*/
@RequestMapping("test2")
@ResponseBody
public String test2(){
List<DeptWithEmployee> list = deptService.queryDeptAndEmployee();
System.out.println(list.size());
return list.get(0).getDeptName();//返回结果成功
}
}
测试结果可以发现,成功的查出了数据并保存到了自定义的结果集中。