mybatis association和collection用法
时间: 2023-08-09 08:11:47 浏览: 122
MyBatis中的association和collection是两种常用的关联映射方式,用于处理实体类之间的一对一和一对多关系。
association用于表示一对一关系,它将一个属性映射到另一个实体类上。例如,一个订单(Order)对象有一个对应的用户(User)对象,可以使用association将用户对象映射到订单对象上。
collection用于表示一对多关系,它将一个属性映射到一个集合上,集合中的元素是另一个实体类。例如,一个部门(Department)对象有多个员工(Employee)对象,可以使用collection将员工对象映射到部门对象上。
具体使用方式如下:
1. association使用方法:
- 在Mapper.xml中使用association标签,指定property属性为要映射的属性名,resultType属性为关联实体类的全限定名,column属性为关联实体类的外键字段名。
```
<resultMap id="orderMap" type="com.example.Order">
<result column="id" property="id"/>
<result column="user_id" property="user.id"/>
<association property="user" resultType="com.example.User" column="user_id">
<result column="username" property="username"/>
<result column="age" property="age"/>
</association>
</resultMap>
```
2. collection使用方法:
- 在Mapper.xml中使用collection标签,指定property属性为要映射的属性名,ofType属性为集合元素的类型,resultMap属性为集合元素的映射规则。
```
<resultMap id="departmentMap" type="com.example.Department">
<result column="id" property="id"/>
<result column="name" property="name"/>
<collection property="employees" ofType="com.example.Employee" resultMap="employeeMap">
<id column="employee_id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
</collection>
</resultMap>
```
其中,employeeMap为Employee类的映射规则。
以上是MyBatis中association和collection的基本用法,需要根据实际情况进行调整和优化。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![md](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)