Mybatis关联、集合查询

关联查询(一对一)

场景:一个作者(Author)有一个博客(Blog)

Blog.java

    public class Blog {
    
    
        private String id;
        private String authorId;
        private Author author;
        //get & set
    }

BlogMapper.xml

<resultMap id="blogResult" type="Blog">
  <association property="author" column="author_id" javaType="Author" select="authorMapper.selectAuthor"/>
</resultMap>

<select id="selectBlog" resultMap="blogResult">
  SELECT * FROM BLOG WHERE ID = #{id}
</select>

AuthorMapper.xml

<mapper namespace="authorMapper" >
    <select id="selectAuthor" resultType="Author">
      SELECT * FROM AUTHOR WHERE ID = #{id}
    </select>
</mapper>

调用BlogMapper.xmlselectBlog 就可以查询关联后的结果。

集合查询(一对多)

场景:一个博客(Blog)有多篇文章(Post)

Blog.java

    public class Blog {
    
    
        private String id;
        private List<Post> posts;
        //get & set
    }

BlogMapper.xml

<resultMap id="blogResult" type="Blog">
  <collection property="posts" javaType="ArrayList" column="id" ofType="Post" select="postMapper.selectPostsForBlog"/>
</resultMap>

<select id="selectBlog" resultMap="blogResult">
  SELECT * FROM BLOG WHERE ID = #{id}
</select>

PostMapper.xml

<mapper namespace="postMapper" >
    <select id="selectPostsForBlog" resultType="Post">
      SELECT * FROM POST WHERE BLOG_ID = #{id}
    </select>
</mapper>

调用BlogMapper.xmlselectBlog就可以查询集合后的结果。

注意:column属性值为数据库中表所对应的列名。

猜你喜欢

转载自blog.csdn.net/u010318957/article/details/72819136