Mybatis中的association级联查询

本文探讨了在Mybatis中如何使用association标签进行级联查询,以封装复杂对象。通过这种方式,可以实现对POJO中对象属性的联合查询,有效地组织数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

POJO中的属性可能会是一个对象,我们可以使用联合查询,并以级联属性的方式封装对象.使用association标签定义对象的封装规则

public class Department {
	private Integer id ; 
	private String departmentName ;
//  省略 get/set方法
}
public class Employee {
	private Integer id ; 
	private String lastName; 
	private String email ;
	private String gender ;
	private Department dept ;
    // 省略 get/set方法
}

使用级联的方式:

<select id="getEmployeeAndDept" resultMap="myEmpAndDept" >
		SELECT e.id eid, e.last_name, e.email,e.gender ,d.id did, d.dept_name FROM tbl_employee e , tbl_dept d   WHERE e.d_id = d.id  AND e.id = #{id}
</select>
	
	<resultMap type="com.atguigu.mybatis.beans.Employee" id="myEmpAndDept">
		<id column="eid" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="email" property="email"/>
		<result column="gender" property="gender"/>
	    <!-- 级联的方式 -->
		<result column="did" property="dept.id"/>
	<result column="dept_name" property="dept.departmentName"/>
</resultMap>

Association的用法

<resultMap type="com.atguigu.mybatis.beans.Employee" id="myEmpAndDept">
		<id column="eid" property="id"/>
		<result column="last_name" property="lastName"/>
		<result column="email" property="email"/>
		<result column="gender" property="gender"/>
		<association property="dept" javaType="com.atguigu.mybatis.beans.Department">
			<id column="did" property="id"/>
			<result column="dept_name" property="departmentName"/>
		</association>
</resultMap>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值