mybatis中collection和association的区别
时间: 2024-05-06 13:20:46 浏览: 11
MyBatis中collection和association都是用来处理关联关系的元素,但是它们的作用和用法有所不同。
1. collection:用于处理一对多的关联关系,即一个实体对象中包含多个子实体对象的情况。collection标签通常用于在一个实体类中包含一个List或Set类型的属性,该属性中包含多个子实体对象。示例:
```xml
<resultMap id="authorMap" type="Author">
<id property="id" column="author_id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<collection property="articles" ofType="Article">
<id property="id" column="article_id"/>
<result property="title" column="title"/>
<result property="content" column="content"/>
</collection>
</resultMap>
```
2. association:用于处理一对一的关联关系,即一个实体对象中包含一个子实体对象的情况。association标签通常用于在一个实体类中包含一个其他实体类类型的属性。示例:
```xml
<resultMap id="articleMap" type="Article">
<id property="id" column="article_id"/>
<result property="title" column="title"/>
<result property="content" column="content"/>
<association property="author" javaType="Author">
<id property="id" column="author_id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
</association>
</resultMap>
```
总结:
collection和association都是用于处理关联关系的元素,但是collection用于处理一对多的关联关系,association用于处理一对一的关联关系。在具体使用时,需要根据实际情况选择合适的标签。