首页 > 解决方案 > 使用 MyBatis XML Mapper 检索数据以在单个查询中填充列表

问题描述

我有三个班级:

public class Customer{
    public Integer idCustomer;
    public String name;
    public String status;
    public Integer idPlant;
    public List<Worker> workers;
}
public class Worker{
    public Integer idWorker;
    public String name;
    public String lastName;
    public Integer status;
}
public class CustomerWorker{
    public Integer idCustomer;
    public Integer idWorker;
}

所以我在 XML 映射器中声明了 resultMap:

<resultMap id="CustomerResultMap" type="Customer">
    <result property="idCustomer" column="idCustomer"/>
    <result property="name" column="name"/>
    <result property="status" column="status"/>
    <result property="idPlant" column="idPlant"/>
    <collection property="workers" resultMap="workerResultMap">
    </collection>
</resultMap>

<resultMap id="WorkerResultMap" type="Worker">
    <result property="idWorker" column="idWorker"/>
    <result property="name" column="name"/>
    <result property="lastName" column="lastName"/>
    <result property="status" column="status"/>
</resultMap>

<resultMap id="CustomerWorkerResultMap" type="CustomerWorker">
    <result property="idCustomer" column="idCustomer"/>
    <result property="idWorker" column="idWorker"/>
</resultMap>

我编写了一个 select 语句来检索所有客户,但此时我将获取所有客户,然后在进一步的迭代中,我为每个客户检索所有工作人员。当然,这个解决方案不起作用,因为它迫使我进行 N+1 次迭代(其中 N 是我的数据库中的客户数量)。

有没有办法编写单个查询以填充工作人员的列表一次?我想到了这样的事情:

 <select id="getCustomers">
  SELECT 
   C.idCustomer,
   C.name,
   C.status,
   C.idPlant,
   (SELECT * 
    FROM Worker W
    INNER JOIN CustomerWorker CW on CW.idWorker = W.idWorker
    WHERE CW.idCustomer = C.idCustomer) as workers
  FROM Customer C 
 </select>

但我不能在 SQL Server 中声明这样的子查询。我确定我在这里搞错了。

标签: javasql-servermybatis

解决方案


推荐阅读