在MyBatis中,association和collection元素都是用來處理一對一和一對多關聯關系的。它們通常用在resultMap中,用來映射查詢結果中的關聯字段。
association元素用來處理一對一關聯關系,通常在resultMap中嵌套使用。示例代碼如下:
<resultMap id="userResultMap" type="User">
<id property="id" column="user_id"/>
<result property="username" column="username"/>
<association property="role" javaType="Role">
<id property="id" column="role_id"/>
<result property="name" column="role_name"/>
</association>
</resultMap>
collection元素用來處理一對多關聯關系,通常在resultMap中嵌套使用。示例代碼如下:
<resultMap id="roleResultMap" type="Role">
<id property="id" column="role_id"/>
<result property="name" column="role_name"/>
<collection property="users" ofType="User">
<id property="id" column="user_id"/>
<result property="username" column="username"/>
</collection>
</resultMap>
在使用association和collection元素時,需要注意:
通過正確使用association和collection元素,可以方便地處理實體類之間的關聯關系,提高數據查詢的靈活性和效率。