首页 > 解决方案 > 在 Mybatis 的另一个结果 Map 中选择 List of Department as Collection

问题描述

Java 8.0 版(Springboot),Oracle 数据库

我有我的java类 -

public class AllEmployee{
List<Employee> employees;
}

public class Employee {
    String globalId;
    int empId;
    String name;
    List<Department> departmentList;
    }
    
public class Department {
    int empId;
    int depId;
    String depValue;
}

MyBatis xml 配置 -

<resultMap id="empMapper" type="Employee">
        <id property="globalId" column="globalId" />
        <result property="empId" column="empId" />
        <result property="name" column="name" />
        <collection property="departmentList" javaType="ArrayList" ofType="Department"/>
        <id property="empId" column="empId" />
        <result property="depId" column="depId" />
        <result property="depValue" column="depValue" />
        </collection>
</resultMap>

<select id="retriveAllEmployees" resultMap="empMapper">
        SELECT ee.empId, ee.name, dt.depId, dt.depValue FROM employee ee
        INNER JOIN department dt on dt.empId = ee.empId
        <where>
            globalId IN
            <foreach collection="globalIdList" item="globalId" separator=", " open="(" close=")">
                #{globalId}
            </foreach>
        </where>
    </select>

正确的 json 输出应该是 -

{
  "employees": [
    {
      "empId": 1,
      "name": "alton",
      "departmentList": [
        {
          "depId": 2,
          "depValue": "fire"
        },
        {
          "depId": 4,
          "depValue": "ice"
        }
      ]
    }
  ]
}

但是在以下 json 格式中得到错误的输出-(外部对象重复多次)

{
  "employees": [
    {
      "empId": 1,
      "name": "alton",
      "departmentList": [
        {
          "depId": 2,
          "depValue": "fire"
        }
      ]
    },
    {
      "empId": 1,
      "name": "alton",
      "departmentList": [
        {
          "depId": 4,
          "depValue": "ice"
        }
      ]
    }
  ]
}

从 mybatis 获取对象后,我可以使用流和对象操作更正响应,但我需要 mybatis 中的正确方法将其直接转换为我们想要的对象。谁能纠正我,我在这个 xml 代码中缺少什么。

标签: oraclecollectionsjava-8mybatisspring-mybatis

解决方案


推荐阅读