关联的多结果集(ResultSet)

属性描述
column当使用多个结果集时,该属性指定结果集中用于与 foreignColumn 匹配的列(多个列名以逗号隔开),以识别关系中的父类型与子类型。
foreignColumn指定外键对应的列名,指定的列将与父类型中 column 的给出的列进行匹配。
resultSet指定用于加载复杂类型的结果集名字。

从版本 3.2.3 开始,MyBatis 提供了另一种解决 N+1 查询问题的方法。

某些数据库允许存储过程返回多个结果集,或一次性执行多个语句,每个语句返回一个结果集。 我们可以利用这个特性,在不使用连接的情况下,只访问数据库一次就能获得相关数据。

在例子中,存储过程执行下面的查询并返回两个结果集。第一个结果集会返回博客(Blog)的结果,第二个则返回作者(Author)的结果。

  1. SELECT * FROM BLOG WHERE ID = #{id}
  2. SELECT * FROM AUTHOR WHERE ID = #{id}

在映射语句中,必须通过 resultSets 属性为每个结果集指定一个名字,多个名字使用逗号隔开。

  1. <select id="selectBlog" resultSets="blogs,authors" resultMap="blogResult" statementType="CALLABLE">
  2. {call getBlogsAndAuthors(#{id,jdbcType=INTEGER,mode=IN})}
  3. </select>

现在我们可以指定使用 “authors” 结果集的数据来填充 “author” 关联:

  1. <resultMap id="blogResult" type="Blog">
  2. <id property="id" column="id" />
  3. <result property="title" column="title"/>
  4. <association property="author" javaType="Author" resultSet="authors" column="author_id" foreignColumn="id">
  5. <id property="id" column="id"/>
  6. <result property="username" column="username"/>
  7. <result property="password" column="password"/>
  8. <result property="email" column="email"/>
  9. <result property="bio" column="bio"/>
  10. </association>
  11. </resultMap>

你已经在上面看到了如何处理“有一个”类型的关联。但是该怎么处理“有很多个”类型的关联呢?这就是我们接下来要介绍的。