Association query (one to one)
Scenario: An author (Author) has a blog (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>
Call selectBlog in BlogMapper.xml to query the associated results.
Collection query (one to many)
Scenario: A blog (Blog) has multiple articles (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>
Call selectBlog in BlogMapper.xml to query the result of the collection.