马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
在Spring Boot中使用MyBatis实现一对多关系时,可以通过XML映射文件来配置。下面我将具体介绍几种实现方式。
基本概念
一对多关系指的是一个实体对象包罗多个子对象聚集的情况,例如:
- 一个部门有多个员工
- 一个订单有多个订单项
- 一个博客有多个批评
实现方式
1. 使用嵌套结果映射(ResultMap)- <!-- DepartmentMapper.xml -->
- <resultMap id="departmentWithEmployeesMap" type="com.example.Department">
- <id property="id" column="dept_id"/>
- <result property="name" column="dept_name"/>
- <!-- 一对多关系配置 -->
- <collection property="employees" ofType="com.example.Employee">
- <id property="id" column="emp_id"/>
- <result property="name" column="emp_name"/>
- <result property="email" column="emp_email"/>
- </collection>
- </resultMap>
- <select id="findDepartmentWithEmployees" resultMap="departmentWithEmployeesMap">
- SELECT
- d.id as dept_id,
- d.name as dept_name,
- e.id as emp_id,
- e.name as emp_name,
- e.email as emp_email
- FROM department d
- LEFT JOIN employee e ON d.id = e.dept_id
- WHERE d.id = #{id}
- </select>
复制代码 2. 使用嵌套查询(Nested Query)- <!-- DepartmentMapper.xml -->
- <resultMap id="departmentMap" type="com.example.Department">
- <id property="id" column="id"/>
- <result property="name" column="name"/>
- <collection
- property="employees"
- column="id"
- ofType="com.example.Employee"
- select="com.example.mapper.EmployeeMapper.findByDepartmentId"/>
- </resultMap>
- <select id="findById" resultMap="departmentMap">
- SELECT id, name FROM department WHERE id = #{id}
- </select>
- <!-- EmployeeMapper.xml -->
- <select id="findByDepartmentId" resultType="com.example.Employee">
- SELECT id, name, email FROM employee WHERE dept_id = #{deptId}
- </select>
复制代码 实体类示例
- // Department.java
- public class Department {
- private Long id;
- private String name;
- private List<Employee> employees;
- // getters and setters
- }
- // Employee.java
- public class Employee {
- private Long id;
- private String name;
- private String email;
- // getters and setters
- }
复制代码 使用注解的替换方案
假如你更喜欢使用注解而不是XML,也可以这样配置:- @Mapper
- public interface DepartmentMapper {
- @Select("SELECT id, name FROM department WHERE id = #{id}")
- @Results({
- @Result(property = "id", column = "id"),
- @Result(property = "name", column = "name"),
- @Result(property = "employees", column = "id",
- many = @Many(select = "com.example.mapper.EmployeeMapper.findByDepartmentId"))
- })
- Department findByIdWithEmployees(Long id);
- }
复制代码 性能考虑
- 嵌套结果映射:单次SQL查询,得当关联数据量不大的情况
- 嵌套查询:多次SQL查询,得当关联数据量大或必要延迟加载的情况
可以通过 fetchType 属性控制加载方式:- <collection
- property="employees"
- column="id"
- ofType="com.example.Employee"
- select="com.example.mapper.EmployeeMapper.findByDepartmentId"
- fetchType="lazy"/> <!-- 或 eager -->
复制代码 以上就是在Spring Boot中MyBatis实现一对多关系的XML配置方式。根据你的具体需求选择符合的方法。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|