当前位置: 代码迷 >> 综合 >> mybatis 一对多映射,多对一映射
  详细解决方案

mybatis 一对多映射,多对一映射

热度:63   发布时间:2023-09-18 19:28:39.0

笔记:仅供自己复习使用,有问题大家可以指出来

1.一对多使用collection

例如mybatis官网官网的实例如下:

<resultMap id="blogResult" type="Blog"><collection property="posts" javaType="ArrayList" column="id" ofType="Post" select="selectPostsForBlog"/>
</resultMap><select id="selectBlog" resultMap="blogResult">SELECT * FROM BLOG WHERE ID = #{id}
</select><select id="selectPostsForBlog" resultType="Post">SELECT * FROM POST WHERE BLOG_ID = #{id}
</select>

主sql为selectBlog,但是它的返回结果是resultMap,我们找到resultMap,它把主sql:selectBlog查询的id又作为了查询条件,同一命名空间下,sql为selectPostsForBlog这条,查询一个博客下有多少帖子;我们得到的结果是博客对象和其对应的帖子,这个应该是封装到一个VO对象里面。这样就实现了关联嵌套查询。

2.多对一使用association

例如mybatis官网官网的实例如下:

<resultMap id="blogResult" type="Blog"><association property="author" column="author_id" javaType="Author" select="selectAuthor"/>
</resultMap><select id="selectBlog" resultMap="blogResult">SELECT * FROM BLOG WHERE ID = #{id}
</select><select id="selectAuthor" resultType="Author">SELECT * FROM AUTHOR WHERE ID = #{id}
</select>

主sql是selectBlog,其返回结果类型为resultMap,我们根据其id找到上面的resultMap,这个和collection相反,把同一个Author的博客归到一类,它后面的子查询(同一命名空间下)selectAuthor找到了Author为同一人的博客,并按Author分类

  相关解决方案