在 MyBatis 中进行多表关联查询时,通常可以通过两种方式来接收多表查询结果:使用嵌套结果映射(Nested Result Mapping)或者使用关联查询(Association Query)。这取决于你的查询需求和数据结构。
以下是Association示例说明:
### 1. 嵌套结果映射(Nested Result Mapping):
假设你有两个实体类:`Order` 和 `User`,并且你希望查询订单信息以及每个订单对应的用户信息。
```xml
<!-- OrderMapper.xml -->
<select id="getOrdersWithUsers" resultType="Order">
SELECT o.*, u.id as user_id, u.username as user_username
FROM orders o
INNER JOIN users u ON o.user_id = u.id
</select>
```
在这个例子中,你将使用一个查询来获取包含订单信息以及嵌套用户信息的结果。在`resultType`中指定主实体类型(这里是`Order`),然后在查询中使用别名来映射嵌套的用户信息。
```java
// Order.java
public class Order {
private int id;
private User user;
// other fields, getters and setters
}
// User.java
public class User {
private int id;
private String username;
// other fields, getters and setters
}
```
### 2. 关联查询(Association Query):
在这种方式中,你可以使用 MyBatis 的关联查询功能,通过在查询语句中嵌套使用`<association>`标签来映射关联的实体。
```xml
<!-- OrderMapper.xml -->
<select id="getOrdersWithUsers" resultMap="OrderWithUserResultMap">
SELECT o.*, u.*
FROM orders o
INNER JOIN users u ON o.user_id = u.id
</select>
<resultMap id="OrderWithUserResultMap" type="Order">
<id property="id" column="id" />
<!-- other fields -->
<association property="user" resultMap="UserResultMap" />
</resultMap>
<resultMap id="UserResultMap" type="User">
<id property="id" column="user_id" />
<result property="username" column="user_username" />
<!-- other fields -->
</resultMap>
```
在这个例子中,你定义了两个`resultMap`,一个用于订单信息,另一个用于用户信息,然后通过`<association>`标签将两者关联起来。使用 `<association>` 子标签,可以处理复杂的多表关联查询,并将关联的实体嵌套映射到主实体中。这些子标签使你能够在查询结果映射中处理对象的关联关系,从而获得更加结构化的数据结果。
以下是Collection示例说明:
当您需要在 MyBatis 中处理一对多关系(一个对象关联多个对象)时,您可以使用 `<collection>` 元素来映射关联表的多个行记录到一个 Java 集合属性中。这通常在数据库模式中具有一对多关系的情况下很有用。
以下是一个使用 `<collection>` 元素的示例:
```xml
<resultMap id="DepartmentWithEmployeesResultMap" type="Department">
<id property="id" column="dept_id"/>
<result property="name" column="dept_name"/>
<collection property="employees" ofType="Employee" resultMap="EmployeeResultMap"/>
</resultMap>
<resultMap id="EmployeeResultMap" type="Employee">
<id property="id" column="emp_id"/>
<result property="name" column="emp_name"/>
<!-- Other employee properties -->
</resultMap>
```
在这个示例中,`Department` 类包含一个名为 `employees` 的集合属性,它被映射到关联的 `Employee` 对象。通过使用 `<collection>` 元素,您可以映射从关联表检索到的多个行记录到一个集合中。
在您的 Java 类中,`Department` 类会有一个 `List<Employee>` 类型的属性,可以容纳多个 `Employee` 对象。
需要注意的是,使用 `<collection>` 元素时,通常需要在查询中使用 JOIN 或其他方式将关联表的数据连接起来,以便 MyBatis 可以将数据正确地映射到集合属性中。
总之,使用 `<collection>` 元素允许您在 MyBatis 中处理一对多关系,使您能够将关联表的多个行记录映射到一个集合属性中,从而更好地表示复杂的数据关系。
这两种方式都可以用来在 MyBatis 中接收多表关联查询的结果。你可以根据数据结构和查询需求来选择合适的方式。无论哪种方式,你都可以得到包含多表关联信息的实体对象或者嵌套的属性。