在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_emailFROM department dLEFT JOIN employee e ON d.id = e.dept_idWHERE 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配置方式。根據你的具體需求選擇合適的方法。