MyBatis一对一关联查询 级联查询

MyBatis一对一关联查询可以使用嵌套结果映射来实现。

举例:用户和用户详情一对一关联,用户mapper接口如下:

public interface UserMapper {
    @Select("SELECT * FROM users")
    @Results({
        @Result(id = true, column = "id", property = "id"),
        @Result(column = "detail_id", property = "detail", 
            one = @One(select = "com.test.mapper.UserDetailMapper.selectDetailById"))
    })
    List<User> selectAll();
}

UserDetailMapper接口如下:

public interface UserDetailMapper {
    @Select("SELECT * FROM user_details WHERE id = #{id}")
    UserDetail selectDetailById(int id);
} 

在selectAll方法中,使用@One注解声明一对一嵌套结果映射,select属性指定的UserDetailMapper.selectDetailById查询用户详情,并映射到User实体的detail属性。

这样,在调用UserMapper.selectAll()时,会自动进行嵌套查询,填充User实体的detail属性,实现一对一关联查询。一对一关联的级联查询,可以在UserInfo Mapper增加方法如下:

@Select("SELECT * FROM users WHERE detail_id = #{id}")
List<User> selectByDetailId(int id);

然后在UserDetailMapper的selectDetailById方法上增加映射:

@Select("SELECT * FROM user_details WHERE id = #{id}")
@Results({
    @Result(id = true, column = "id", property = "id"),
    @Result(column = "id", property = "users", 
            many = @Many(select = "com.test.mapper.UserMapper.selectByDetailId")) 
})
UserDetail selectDetailById(int id); 

这里使用@Many注解定义多对一集合嵌套结果映射,当查询某个用户详情时,会自动进行关联查询users,实现级联查询。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发

请登录后发表评论