假设我有两个简单的表格:
Article: id | text
Comment: id | articleId | text
两个DTO课程:
class Article {
private int id;
private String text;
private List<Comment> comments;
...
}
class Comment {
private int id;
private String text;
private Article article;
...
}
我想通过id选择一篇文章及其所有评论。关键要求是从查询返回的Article实例必须是SAME实例,因为它的所有注释都是getArticle()。
是否可以映射这个?我能想到的映射:
<resultMap id="ArticleResult" class="Article">
<result column="id" property="id" />
<result column="text" property="text" />
<result column="id" property="comments" select="findCommentsByArticleId" />
</resultMap>
<resultMap id="CommentResult" class="Comment">
<result column="id" property="id" />
<result column="text" property="text" />
<result column="articleId" property="article" select="findArticleById" />
</resultMap>
<select id="findArticleById" resultMap="ArticleResult" parameterClass="int">
SELECT * FROM Article WHERE id = #value#
</select>
<select id="findCommentsByArticleId" resultMap="CommentResult" parameterClass="int">
SELECT * FROM Comment WHERE articleId = #value#
</select>
但首先,它看起来像是一个循环,第二,我上面提到的关键要求将无法满足。
答案 0 :(得分:0)
我认为关键是在resultMap中,应该使用而不是<result>
。
<resultMap id="ParentResult" groupBy="id">
<result property="id" column="ID" />
...
<collection property="children" javaType="ArrayList" ofType="Child" resultMap="ChildResult" />
</resultMap>
<resultMap id="ChildResult">
<result property="id" column="ID" />
<association property="parentId" foreignColumn="PARENT_ID" resultMap="ParentResult" />
...
</result>