在 MyBatis 中进行一对一、一对多的关联查询,可以通过 association
和 collection
标签配合 resultMap
进行配置。下面是一对一和一对多关联查询的配置示例:
假设有两个表:user
和 user_profile
,user_profile
中存储了用户的额外信息。
public interface UserMapper {
User getUserWithProfile(int userId);
}
假设有两个表:post
和 comment
,一个帖子对应多个评论。
public interface PostMapper {
Post getPostWithComments(int postId);
}
以上配置通过 association
和 collection
标签,在 resultMap
中定义了一对一和一对多的关联关系,实现了查询结果的映射。在 SQL 查询语句中,通过 LEFT JOIN
等方式关联查询相关表的数据,并使用 resultMap
将结果映射到 Java 对象中。
Proudly powered by WordPress