Mybaits表关系之1对1
将查询出来的字段值,装填到对象属性中,完成对象属性的创建和赋值。查询出来的每一行都是一个对象,并且对象有一个对象属性,需要指定装填。
emp对象中有一个dept对象
dept对象
public class Dept {
private Integer deptId;
private String deptName;
private String deptDesc;
emp对象
public class Emp {
private Integer empId;
private String empName;
private Integer empAge;
// 表示一个 Emp对象具有一个Dept对象
private Dept dept;
emp对象的查询映射
<resultMap type="emp" id="baseMap">
<id column="emp_id" property="empId"/>
<result column="emp_name" property="empName"/>
<result column="emp_age" property="empAge"/>
<!-- 一对一的关联配置 -->
<association property="dept" javaType="dept">
<id column="dept_id" property="deptId"/>
<result column="dept_name" property="deptName"/>
<result column="dept_desc" property="deptDesc"/>
</association>
</resultMap>
<select id="query" resultMap="baseMap">
SELECT
t1.emp_id
,t1.emp_name
,t1.emp_age
,t2.dept_id
,t2.dept_name
,t2.dept_desc
FROM
t_emp t1
LEFT JOIN t_dept t2
ON t1.dept_id = t2.dept_id
</select>
测试一下
@Test
public void test2() throws IOException {
InputStream in = Resources.getResourceAsStream("mybatis-cfg.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = factory.openSession(true);
EmpMapper dao = session.getMapper(EmpMapper.class);
List<Emp> list = dao.query();
for (Emp emp : list) {
System.out.println(emp+" "+emp.getDept());
}
session.close();
}
输出打印粘贴
[QC] DEBUG [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(159) | ==> Preparing: SELECT t1.emp_id ,t1.emp_name ,t1.emp_age ,t2.dept_id ,t2.dept_name ,t2.dept_desc FROM t_emp t1 LEFT JOIN t_dept t2 ON t1.dept_id = t2.dept_id
[QC] DEBUG [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(159) | ==> Parameters:
[QC] DEBUG [main] org.apache.ibatis.logging.jdbc.BaseJdbcLogger.debug(159) | <== Total: 8
Emp [empId=1, empName=孙悟空, empAge=13] Dept [deptId=3, deptName=研发部, deptDesc=yfb]
Emp [empId=2, empName=刘德华, empAge=15] Dept [deptId=2, deptName=销售部, deptDesc=xsb]
Emp [empId=3, empName=刘诗诗, empAge=16] Dept [deptId=2, deptName=销售部, deptDesc=xsb]
Emp [empId=4, empName=古天乐, empAge=15] Dept [deptId=1, deptName=小卖部, deptDesc=xmb]
Emp [empId=5, empName=水娃, empAge=13] Dept [deptId=4, deptName=行政部, deptDesc=xzb]
Emp [empId=6, empName=宙斯, empAge=16] Dept [deptId=4, deptName=行政部, deptDesc=xzb]
Emp [empId=7, empName=美杜莎, empAge=17] Dept [deptId=3, deptName=研发部, deptDesc=yfb]
Emp [empId=8, empName=耶稣, empAge=15] Dept [deptId=1, deptName=小卖部, deptDesc=xmb]
项目打包 提取码:qzq7
环境:eclipse,maven