java - 使用 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 中声明这样的子查询。我确定我在这里搞错了。
解决方案
推荐阅读
- node.js - 使用 git bash 在 Windows 中运行 npm test 命令时出错
- swift - 如何在 NSView 子类中绘制两行文本?(macOS 系统托盘)
- python - 使用粗糙集理论进行特征选择
- core-data - 带有 NSPredicate 的 FetchRequest 不会在新条目上更新
- java - 无法使用 Apache CXF 库 Maven 从 WSDL 生成 POJO
- android - Android 上的内部、外部、可移动和可采用存储的当前状态是什么?
- flutter - 如何在列表视图内滚动时修复顶部的选项卡?
- excel - Excel Power Query 刷新查询后将日期值更改为通用数字(来自在线资源)
- python-3.x - 服务器回复:403。如何解决这个问题?
- google-cloud-platform - 私人访问主页