开发喵星球

MyBatis 一对一、一对多的关联查询如何配置?

在 MyBatis 中进行一对一、一对多的关联查询,可以通过 associationcollection 标签配合 resultMap 进行配置。下面是一对一和一对多关联查询的配置示例:

一对一关联查询:

假设有两个表:useruser_profileuser_profile 中存储了用户的额外信息。

  1. XML 配置:


  
  
  

  
  
    
    
    
  




  1. Java Mapper 接口:
public interface UserMapper {
    User getUserWithProfile(int userId);
}

一对多关联查询:

假设有两个表:postcomment,一个帖子对应多个评论。

  1. XML 配置:


  
  
  

  
  
    
    
    
  




  1. Java Mapper 接口:
public interface PostMapper {
    Post getPostWithComments(int postId);
}

以上配置通过 associationcollection 标签,在 resultMap 中定义了一对一和一对多的关联关系,实现了查询结果的映射。在 SQL 查询语句中,通过 LEFT JOIN 等方式关联查询相关表的数据,并使用 resultMap 将结果映射到 Java 对象中。

Proudly powered by WordPress