gpt4 book ai didi

hibernate - 如何使用 JPA/Hibernate 检索实体列表 + 附加值?

转载 作者:行者123 更新时间:2023-12-04 06:38:01 25 4
gpt4 key购买 nike

有两个表,report 和reportcomment。每个报告评论(通过外键)分配给一个报告,因此一个报告有零到多个报告评论。
如果我需要一个列表,它为我提供了所有报告以及每个报告的相应评论数量,我将执行以下操作(使用 SQL):

SELECT r.*, c.cnt
FROM report r
LEFT JOIN (
SELECT ir.id AS report_id, COUNT(ic.id) AS cnt
FROM report ir
INNER JOIN reportcomment ic ON ir.id = ic.report_id
GROUP BY ir.id
) c ON c.report_id = r.id

我想用 JPA/Hibernate 检索这样一个列表并存储 c.cnt在我的某处 Report实体对象。
这怎么可能实现?

最佳答案

我认为最简单的方法是在 Report 中创建一个 transient 字段并手动转换由适当查询返回的元组,如下所示:

List<Object[]> tuples = em.createQuery(
"SELECT r, COUNT(c) " +
"FROM ReportComment c RIGHT JOIN c.report r" +
"GROUP BY r.id, ...").getResultList();

List<Report> reports = new ArrayList<Report>();
for (Object[] tuple: tuples) {
Report r = (Report) tuple[0];
r.setCommentCount((Long) tuple[1]);
reports.add(r);
}

关于hibernate - 如何使用 JPA/Hibernate 检索实体列表 + 附加值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4627799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com