在MyBatis中,进行多表联查时关联关系主要有这几种:一对多,多对一,多对多,还有一种自关联
1.一对多:有两种方式
(1)用一条sql语句进行查询 (以查询部门和员工为案例)
首先创建实体类
package entity; import java.util.List; /** * Created by mycom on 2018/2/26. */ public class Dept {//部门 private Integer deptNo; private String deptName; private List<Emp> emps; public List<Emp> getEmps() { return emps; } public void setEmps(List<Emp> emps) { this.emps = emps; } public Integer getDeptNo() { return deptNo; } public void setDeptNo(Integer deptNo) { this.deptNo = deptNo; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } }
然后创建部门接口以及对应的xml文件
package dao; import entity.Dept; import entity.Emp; import java.util.List; /** * Created by mycom on 2018/2/26. */ public interface IDeptDao { //根据部门编号获得部门名称 员工名称 单条sql public Dept getEmpByDeptNo(int deptNo); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="dao.IDeptDao"> <resultMap id="deptMaper" type="Dept"> <id column="d" property="deptNo"></id> <result column="deptName" property="deptName"></result> <collection property="emps" ofType="Emp"> <id column="empNo" property="empNo"></id> <result column="empName" property="empName"></result> </collection> </resultMap> <!--查询部门和员工 单条sql语句方案--> <select id="getEmpByDeptNo" resultMap="deptMaper"> SELECT dept.deptNo as d ,deptName,empName FROM dept,emp WHERE dept.`deptNo`=emp.`deptNo` AND dept.`deptNo`=#{deptNo} </select> </mapper>
编写测试类
//查询部门和员工 单条sql
@Test
public void oneToMany(){
SqlSession sqlSession = MyBatisUtil.getSession();
IDeptDao mapper = sqlSession.getMapper(IDeptDao.class);
Dept dept = mapper.getEmpByDeptNo(1);
System.out.println("部门名称"+dept.getDeptName());
for (Emp emp:dept.getEmps()) {
System.out.println(emp.getEmpName());
}
sqlSession.close();
}