mybatis 关联查询 含有集合的嵌套查询 并传多个参数

前提:

三个表:公司,部门,员工   。(部门和员工表中 均有 companyId,departmentId 两字段)

要求:

查询部门信息和本部门中所有员工的信息, 


java实体类:

public class Department {
	/** 部门id */
	private int departmentId;
	/** 部门名 */
	private String departmentName;
	/** 部门经理 */
	private String departmentManagerName;
	/** 部门所属公司ID */
	private int companyId;
	/** 关联属性 ,用于封装部门对应的员工信息 */
	private List<Employee> employees;

DAO:

public interface DepartmentDao {
	/**
	 * 根据公司ID、部门ID 查询部门信息 和 本部门所有员工信息
	 * @param comId
	 * @param deptId
	 * @return Department类
	 */
	public Department findDeptInfo(@Param("companyId") int comId,@Param("departmentId") int deptId);

mapper.xml:

<sql id="departmentAllField">departmentId,departmentName,departmentManagerName,companyId</sql>
<sql id="employeeAllField">employeeId,employeeName,sex,age,address,phoneNumber,companyId,departmentId,job</sql>

<select id="findDeptInfo" resultMap="deptMap"> 
	select <include refid="departmentAllField" /> from department where companyId=#{companyId} and departmentId=#{departmentId}; 
</select>

<resultMap type="com.demo.model.Department" id="deptMap">
	<!-- 传递两个字段 -->
	<collection property="employees" javaType="ArrayList" 
	 column="{companyId = companyId,departmentId=departmentId}" ofType="com.demo.model.Employee" select="findEmpsByDept"/>
</resultMap>

<select id="findEmpsByDept" resultType="com.demo.model.Employee">
	select <include refid="employeeAllField" /> from employee
	 where companyId=#{companyId} and departmentId=#{departmentId}; 
</select>

Test类:

public class TestFindDeptInfo {
	static AbstractApplicationContext ac;
	SqlSessionFactory factory;
	SqlSession session;
	DepartmentDao deptDao;
	
	@Before
	public void init(){
		String conf = "applicationContext.xml";
		ac = new ClassPathXmlApplicationContext(conf);
		factory = ac.getBean("ssf",SqlSessionFactory.class );
		session = factory.openSession();
	}
	@Test	
	public void testDao1(){
		deptDao = session.getMapper(DepartmentDao.class);
		Department dept = deptDao.findDeptInfo(6201, 1);
		System.out.println(dept);
	}
}



以上为基本思路,不提供详细代码。代码运行成功。

### MyBatis嵌套查询与嵌套集合的用法及区别 #### 一、嵌套查询 嵌套查询是指在一个 `resultMap` 的定义中,通过 `<association>` 或者 `<collection>` 标签中的 `select` 属性来指定另一个查询语句。这种方式会触发额外的一次数据库查询操作。 - **实现方式** 在 `resultMap` 定义中使用 `<association select="..." />` 或 `<collection select="...">...</collection>` 来执行子查询[^1]。例如: ```xml <resultMap type="com.example.MyBatis.dao.model.Person" id="personResultMap"> <id property="id" column="id"/> <result property="name" column="name"/> <!-- 关联查询 --> <association property="address" column="address_id" select="selectAddressById"/> </resultMap> <select id="selectPersonById" resultMap="personResultMap"> SELECT * FROM person WHERE id = #{id} </select> <select id="selectAddressById" resultType="com.example.MyBatis.dao.model.Address"> SELECT * FROM address WHERE id = #{id} </select> ``` - **特点** - 数据库会被多次访问,因为每次都需要单独发起子查询。 - 更适合用于复杂逻辑处理或者当父表和子表之间存在一对多关系时,且子表的数据量较小时[^4]。 --- #### 二、嵌套集合 嵌套集合则是指在同一个 SQL 查询中完成所有的数据获取工作,利用 `JOIN` 将多个表的数据组合在一起。之后,在 `resultMap` 中通过 `<collection>` 和 `<association>` 映射这些联合查询的结果。 - **实现方式** 使用单条 SQL 进行联合查询映射到复杂的对象结构中[^3]。例如: ```xml <resultMap type="com.example.MyBatis.dao.model.Course" id="courseWithSectionsAndLessons"> <id property="uuid" column="course_uuid"/> <result property="title" column="course_title"/> <!-- 节点集合 --> <collection property="sections" ofType="com.example.MyBatis.dao.model.Section"> <id property="uuid" column="section_uuid"/> <result property="name" column="section_name"/> <!-- 子节点集合 --> <collection property="lessons" ofType="com.example.MyBatis.dao.model.Lesson"> <id property="uuid" column="lesson_uuid"/> <result property="title" column="lesson_title"/> </collection> </collection> </resultMap> <select id="getCourseDetail" resultMap="courseWithSectionsAndLessons"> SELECT * FROM course c LEFT JOIN section s ON c.uuid = s.course_uuid LEFT JOIN lesson l ON s.uuid = l.section_uuid WHERE c.uuid = #{courseId} </select> ``` - **特点** - 只需一次数据库查询即可完成所有数据加载。 - 对于大数据量的情况可能更高效,但也可能导致 SQL 复杂度增加以及性能瓶颈(如笛卡尔积等问题)[^3]。 --- #### 三、两者的对比分析 | 特性 | 嵌套查询 | 嵌套集合 | |-------------------|----------------------------------|----------------------------------| | **数据库交互次数** | 多次 | 单次 | | **适用场景** | 父子表间一对一或多对一时,子表数据较少 | 当需要一次性获取大量父子关联数据时 | | **SQL 编写难度** | 较低 | 较高(涉及多表连接) | | **性能影响因素** | 如果子查询过多可能会降低效率 | 若返回记录数过大,则内存占用较高 | --- #### 四、总结 如果希望减少 SQL 的复杂性和提高可读性,可以选择嵌套查询;而如果追求更高的查询效率且能够接受一定的开发成本提升,则可以考虑采用嵌套集合的方式[^2]。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值