You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MyBatis无法分离无关联ResultSet问题咨询

MyBatis多结果集查询数据分离问题解决方案

问题分析

当前代码存在两个核心问题导致Movie字段直接暴露在DivideOut实例中,且数据未按预期存入独立列表:

  1. resultMap中开启了autoMapping="true",MyBatis会自动将第一个结果集(movies)的列直接映射到DivideOut实例,而非通过collection配置存入指定列表。
  2. Mapper方法返回类型为List<DivideOut>,MyBatis会自动对两个结果集的行做笛卡尔积关联,生成3*2=6个DivideOut实例,而非将所有Movie/Artist分别存入单个DivideOut的两个列表。

解决方案

1. 修正DivideOut实体类

明确列表泛型类型,避免使用List<Object>:

public class DivideOut {
  public List<Movie> movie;
  public List<Artist> artist;

  @Override
  public String toString() {
    return "DivideOut{" +
      "movie=" + movie +
      ", artist=" + artist +
      '}';
  }
}

2. 调整ResultMap配置

关闭自动映射,避免无关字段被映射到DivideOut:

<resultMap id="multipleQueriesResult" type="DivideOut" autoMapping="false">
    <collection property="movie"
                ofType="Movie"
                javaType="list"
                resultSet="movies">
      <id property="id" column="mId"/>
      <result property="name" column="mName"/>
      <result property="year" column="mYear"/>
    </collection>

    <collection property="artist"
                ofType="Artist"
                javaType="list"
                resultSet="artists">
      <id property="id" column="aId"/>
      <result property="name" column="aName"/>
    </collection>
</resultMap>

3. 修改Mapper接口方法

将返回类型改为单个DivideOut实例,确保所有Movie和Artist数据存入同一个对象的两个列表:

DivideOut selectMultiple();

4. 优化SQL语句(可选)

简化SQL Server的CALLABLE语句写法,无需嵌套BEGIN...END:

<select id="selectMultiple" resultSets="movies,artists" resultMap="multipleQueriesResult" statementType="CALLABLE">
    SELECT M.ID_ AS mId, M.NAME_ AS mName, M.YEAR_ AS mYear FROM TestMyBatis.dbo.Movie AS M;
    SELECT A.ID_ AS aId, A.NAME_ AS aName FROM TestMyBatis.dbo.Artist AS A;
</select>

修正后的预期结果

执行后将得到单个DivideOut实例,包含所有Movie和Artist的独立列表:

DivideOut{movie=[Movie{id=1, name=Movie1, year=2020}, Movie{id=2, name=Movie2, year=2008}, Movie{id=3, name=Movie3, year=1988}], artist=[Artist{id=1, name='John'}, Artist{id=2, name='Jane'}]}

内容的提问来源于stack exchange,提问作者MHSaffari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 17:20:36