一对多的情况下,查询。 Dept中增加变量
private List<Emp> emps;
复制代码
这是最终的Dept
package com.mybatis.pojo;
import java.util.List;
public class Dept {
private int deptno;
private String dname;
private String location;
private List<Emp> emps;
省略了getter和setter
@Override
public String toString() {
StringBuilder sb = new StringBuilder("" + deptno + " " + dname + " " + location);
if (emps != null) {
for (Emp emp : emps) {
sb.append("\n" + emp.toString());
}
}
return sb.toString();
}
}
复制代码
这是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.mybatis.mapper.DeptMapper">
<resultMap id="Dept_base_resultmap" type="com.mybatis.pojo.Dept">
<id column="deptno" property="deptno"/>
<result column="dname" property="dname"/>
<result column="location" property="location"/>
</resultMap>
<resultMap id="Dept_sub_resultmap" type="com.mybatis.pojo.Dept" extends="Dept_base_resultmap">
<collection property="emps" ofType="com.mybatis.pojo.Emp">
<id column="empno" property="empno"/>
<result column="ename" property="ename"/>
<result column="deptno" property="deptno"/>
</collection>
</resultMap>
<select id="getDept" resultMap="Dept_base_resultmap" parameterType="_int">
select * from dept where deptno=#{deptno}
</select>
<select id="getDetpAndEmps" resultMap="Dept_sub_resultmap" parameterType="_int">
select d.deptno,
d.dname,
d.location,
e.empno,
e.ename,
e.deptno
from dept d left join emp e
on d.deptno=e.deptno
where d.deptno=#{deptno};
</select>
</mapper>
复制代码
这是最后的Test类
import com.mybatis.mapper.DeptMapper;
import com.mybatis.pojo.Dept;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.io.Reader;
public class DeptTest {
private static SqlSessionFactory sqlSessionFactory = null;
@BeforeClass
public static void setUpClass() {
try {
String resource = "sqlMapConfig.xml";
Reader reader = Resources.getResourceAsReader(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//todo 增加字段之后这个就不能用了么?
@Test
public void testGetDept() {
SqlSession session = sqlSessionFactory.openSession();
DeptMapper mapper = session.getMapper(DeptMapper.class);
Dept dept = mapper.getDept(1);
System.out.println(dept.toString());
}
@Test
public void testGetDeptAndEmps() {
SqlSession session = sqlSessionFactory.openSession();
DeptMapper mapper = session.getMapper(DeptMapper.class);
Dept dept = mapper.getDetpAndEmps(2);
System.out.println(dept.toString());
}
}
复制代码