0

假设我有两个简单的表:

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 实例必须与其所有注释 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>

但首先,这对我来说似乎是一个循环,其次,我上面提到的关键要求不会得到满足。

4

1 回答 1

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>
于 2014-05-28T21:47:48.620 回答