一、前言
上一章节《老司机学习MyBatis之如何使用association解决一对一关联查询》,我们介绍了MyBatis使用association通过嵌套查询和分段查询两种方式在查询User表的时候关联查询出Role表的信息,我们发现association针对的是一对一的这种关联,那么如果是一对多的关系呢?比如:查询部门信息时,查询出部门下面的所有员工信息呢?这个时候我们使用association是不能实现我们的要求,这时候我们要使用另外一个属性collection来实现这个要求。我们使用collection时候也跟前面使用association时一样,包括嵌套查询和分段查询两种方式,下面我们通过代码案例来说明这两种方式是如何配置的。
二、案例
完整的工程目录如下:
在MySQL数据库新建两张数据库表t_emp和t_dept,并插入若干条数据
CREATE TABLE t_emp (
id int(10) NOT NULL AUTO_INCREMENT,
emp_name varchar(100) DEFAULT NULL,
dept_id int(10),
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
INSERT INTO t_emp(emp_name,dept_id) VALUES ('queen', 1);
INSERT INTO t_emp(emp_name,dept_id) VALUES ('king', 1);
INSERT INTO t_emp(emp_name,dept_id) VALUES ('tom', 2);
INSERT INTO t_emp(emp_name,dept_id) VALUES ('james', 3);
INSERT INTO t_emp(emp_name,dept_id) VALUES ('paul', 3);
=========================================================
CREATE TABLE t_dept (
id int(10) NOT NULL AUTO_INCREMENT,
dept_name varchar(20) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
INSERT INTO t_dept(dept_name) VALUES ('开发部');
INSERT INTO t_dept(dept_name) VALUES ('市场部');
INSERT INTO t_dept(dept_name) VALUES ('行政部');
Emp实体类
public class Emp {
// ID,唯一性
private int id;
// 用户名
private String empName;
// 部门ID
private int deptId;
public Emp() {
}
public Emp(int id, String empName, int deptId) {
this.id = id;
this.empName = empName;
this.deptId = deptId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
@Override
public String toString() {
return "Emp [id=" + id + ", empName=" + empName + ", deptId="
+ deptId + "]";
}
}
Dept实体类
public class Dept {
private int id;
private String deptName;
private List<Emp> empList;
public Dept() {
}
public Dept(int id, String deptName, List<Emp> empList) {
this.id = id;
this.deptName = deptName;
this.empList = empList;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public List<Emp> getEmpList() {
return empList;
}
public void setEmpList(List<Emp> empList) {
this.empList = empList;
}
@Override
public String toString() {
return "Dept [id=" + id + ", deptName=" + deptName + "]";
}
}
配置文件log4j.properties
log4j.rootLogger=DEBUG,A1
log4j.logger.com.queen = DEBUG
log4j.logger.org.mybatis = DEBUG
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n
配置文件db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=root
配置文件mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<properties resource="db.properties"></properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="DeptMapper.xml" />
</mappers>
</configuration>
新建接口类DeptMapper.java,增加接口方法getDeptById
public interface DeptMapper {
/**
* 根据ID查询Dept信息,返回一条记录Dept
* @param id
* @return
*/
public Dept getDeptById(int id);
}
首先我们来看一下嵌套查询,DeptMapper.xml配置文件如下
<?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="com.queen.mybatis.mapper.DeptMapper">
<resultMap type="com.queen.mybatis.bean.Dept" id="deptMap">
<id column="mid" property="id"/>
<result column="deptName" property="deptName"/>
<!-- collection定义集合类型的属性封装规则
ofType:指定集合里面的元素类型
-->
<collection property="empList" ofType="com.queen.mybatis.bean.Emp">
<!-- 定义这个集合中元素的封装规则 -->
<id column="nid" property="id"/>
<result column="empName" property="empName"/>
<result column="deptId" property="deptId"/>
</collection>
</resultMap>
<select id="getDeptById" resultMap="deptMap">
SELECT m.id mid, m.dept_name deptName,n.id nid,
n.emp_name empName,n.dept_id deptId
FROM t_dept m
LEFT JOIN t_emp n ON m.id = n.dept_id
WHERE
m.id = #{id}
</select>
</mapper>
新增测试类MyBatisTest,添加测试方法testGetDeptByCollection
@Test
public void testGetDeptByCollection() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try {
DeptMapper mapper = openSession.getMapper(DeptMapper.class);
Dept dept = mapper.getDeptById(1);
System.out.println(dept);
System.out.println(dept.getEmpList());
} finally {
openSession.close();
}
}
控制台打印结果如下
2017-08-10 22:20:32,961 [main] [com.queen.mybatis.mapper.DeptMapper.getDeptById]-[DEBUG] ==> Preparing: SELECT m.id mid, m.dept_name deptName,n.id nid, n.emp_name empName,n.dept_id deptId FROM t_dept m LEFT JOIN t_emp n ON m.id = n.dept_id WHERE m.id = ?
2017-08-10 22:20:33,019 [main] [com.queen.mybatis.mapper.DeptMapper.getDeptById]-[DEBUG] ==> Parameters: 1(Integer)
2017-08-10 22:20:33,070 [main] [com.queen.mybatis.mapper.DeptMapper.getDeptById]-[DEBUG] <== Total: 2
Dept [id=1, deptName=开发部]
[Emp [id=1, empName=queen, deptId=1], Emp [id=2, empName=king, deptId=1]]
这样我们可以通过collection实现一对多这种情况的数据封装
接下来我们介绍第二种:使用collection进行分步查询,跟上个章节使用assocication一样,即我们查完Dept表数据后,我们在根据查到的Dept的ID查询Emp表数据。分段分多条SQL执行。
新建一个接口类EmpMapper,新增接口方法getEmpListByDeptId
public interface EmpMapper {
/**
* 根据部门ID查询该部门下的所有员工信息
* @param id
* @return
*/
public List<Emp> getEmpListByDeptId(int deptId);
}
新建一个EmpMapper.xml文件,配置如下
<?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="com.queen.mybatis.mapper.EmpMapper">
<select id="getEmpListByDeptId" resultType="com.queen.mybatis.bean.Emp">
select id,emp_name empName,dept_id deptId from t_emp where dept_id=#{deptId}
</select>
</mapper>
修改DeptMapper文件,新增一个方法getDeptByIdStep
/**
* 根据ID查询Dept信息,返回一条记录Dept,分步查询
* @param id
* @return
*/
public Dept getDeptByIdStep(int id);
修改DeptMapper.xml文件,增加如下配置
<!-- 以下使用collection的分步查询 -->
<resultMap type="com.queen.mybatis.bean.Dept" id="deptMapStep">
<id column="id" property="id"/>
<result column="dept_name" property="deptName"/>
<!--将查到的部门ID传递给getEmpListByDeptId方法-->
<collection property="empList" select="com.queen.mybatis.mapper.EmpMapper.getEmpListByDeptId"
column="id">
</collection>
</resultMap>
<select id="getDeptByIdStep" resultMap="deptMapStep">
select id, dept_name from t_dept where id=#{id}
</select>
修改测试类MyBatisTest,添加测试方法testGetDeptByCollectionStep
@Test
public void testGetDeptByCollectionStep() throws IOException {
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try {
DeptMapper mapper = openSession.getMapper(DeptMapper.class);
Dept deptStep = mapper.getDeptByIdStep(1);
System.out.println(deptStep);
System.out.println(deptStep.getEmpList());
} finally {
openSession.close();
}
}
注意:DeptMapper.xml和EmpMapper.xml等映射文件都用配置到mybatis-config.xml文件中,否则会报错。
<mappers>
<mapper resource="DeptMapper.xml" />
<mapper resource="EmpMapper.xml" />
</mappers>
控制台打印结果如下
2017-08-10 22:30:15,158 [main] [com.queen.mybatis.mapper.DeptMapper.getDeptByIdStep]-[DEBUG] ==> Preparing: select id, dept_name from t_dept where id=?
2017-08-10 22:30:15,217 [main] [com.queen.mybatis.mapper.DeptMapper.getDeptByIdStep]-[DEBUG] ==> Parameters: 1(Integer)
2017-08-10 22:30:15,280 [main] [com.queen.mybatis.mapper.EmpMapper.getEmpListByDeptId]-[DEBUG] ====> Preparing: select id,emp_name empName,dept_id deptId from t_emp where dept_id=?
2017-08-10 22:30:15,281 [main] [com.queen.mybatis.mapper.EmpMapper.getEmpListByDeptId]-[DEBUG] ====> Parameters: 1(Integer)
2017-08-10 22:30:15,283 [main] [com.queen.mybatis.mapper.EmpMapper.getEmpListByDeptId]-[DEBUG] <==== Total: 2
2017-08-10 22:30:15,284 [main] [com.queen.mybatis.mapper.DeptMapper.getDeptByIdStep]-[DEBUG] <== Total: 1
Dept [id=1, deptName=开发部]
[Emp [id=1, empName=queen, deptId=1], Emp [id=2, empName=king, deptId=1]]
从上述打印结果,可以看到控制台打印了两段SQL语句,一句用来查询Dept部门信息,另外一句用来查询Emp员工信息,实现了分步查询的效果,且控制台打印结果正常。
=======欢迎大家拍砖,小手一抖,多多点赞哟!=======
版权声明:本文为博主原创文章,允许转载,但转载必须标明出处。