能提供一个MyBatis中实现一对一或多对多关联映射的具体教程案例吗?
时间: 2024-12-21 21:21:59 浏览: 3
SpringBoot中mybatis表关联映射关系(一对多嵌套:结果方式)
在MyBatis中,实现一对一或多对多关联映射通常涉及SQL方言(如XML配置文件或注解)、 resultMap 和 selectManyMap 等元素。这里我会给出一个简单的例子:
### 一对一关联映射
假设我们有两个实体:User 和 Address,用户有一个唯一的Address。
1. 定义实体类:
```java
public class User {
private Integer id;
private String name;
private Address address;
// getters and setters
}
public class Address {
private Integer id;
private String street;
// getters and setters
}
```
2. MyBatis XML 映射文件 (UserMapper.xml):
```xml
<mapper namespace="com.example.UserMapper">
<resultMap id="UserResult" type="User">
<id property="id" column="user_id"/>
<result property="name" column="user_name"/>
<association property="address" javaType="Address">
<selectKey keyProperty="id" resultType="Integer" order="AFTER">
SELECT LAST_INSERT_ID() AS id
</selectKey>
<result property="street" column="address_street"/>
</association>
</resultMap>
<!-- 用户查询其地址 -->
<select id="getUserWithAddress" resultMap="UserResult">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
```
3. 使用时,注入 UserMapper 调用 `getUserWithAddress` 查询:
```java
UserMapper mapper = new SqlSessionTemplate(sessionFactory.openSession()).getMapper(UserMapper.class);
User user = mapper.getUserWithAddress(userId);
```
### 多对多关联映射(通过关联表)
假设有 Products 和 Categories,一个产品可以有多类别,一个类别也可以包含多个产品,中间表为 product_category。
1. Entity 类
```java
public class Product {
private Integer id;
private String name;
private List<Category> categories; // ManyToOne relationship
// getters and setters
}
public class Category {
private Integer id;
private String name;
private List<Product> products; // ManyToOne relationship
// getters and setters
}
```
2. 映射文件(ProductMapper.xml)
```xml
<select id="findProductsByCategoryIds" parameterType="List<Integer>" resultMap="ProductResult">
SELECT p.* FROM product p
LEFT JOIN product_category pc ON p.id = pc.product_id
LEFT JOIN category c ON pc.category_id = c.id
WHERE c.id IN
<foreach item="categoryId" index="index" collection="categoryIds" open="(" separator="," close=")">
#{categoryId}
</foreach>
</select>
<resultMap id="ProductResult" type="Product">
<!-- ... -->
<collection property="categories" ofType="Category">
<id property="id" column="category_id"/>
<result property="name" column="category_name"/>
</collection>
</resultMap>
```
使用时,调用 `findProductsByCategoryIds`:
```java
List<Integer> categoryIds = ...;
List<Product> products = mapper.findProductsByCategoryIds(categoryIds);
```
阅读全文