我有一个表ROOT和一个包含与ROOT相关的行的表CHILDREN。
我想为ROOT的每一行检索一个包含ROOT对象的对象以及与CHILDREN表中的ROOT.id相关的行数。
这可以在SQL中很容易地实现,但我想知道如何在JPQL中编写它
在SQL中:
SELECT r.*, (SELECT COUNT(c.i_id) FROM children c WHERE c.rootId = r.id) FROM root r;
我试图在JPA中重写它,但它仍然失败并出现以下错误
Caused by: org.hibernate.HibernateException: Errors in named queries: xxx
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate
appropriate constructor on class RootExtended...
Java类:
package plop; public class RootExtended{ private Root root; private Long count; public RootExtended(final Root root, final Long count) { this.root= root; this.count= count; } // getters and setters to follow }
JPQL:
SELECT new plop.RootExtended(r, (SELECT count(c.id) FROM Child as c WHERE c.rootId = r.id ) ) FROM Root as r
有什么想法吗?
答案 0 :(得分:0)
我认为不允许在JPA的SELECT
部分中使用子查询(至少版本< = 2),因为它们仅限于WHERE和HAVING子句。有关详细信息,请参阅this。
作为解决方案,您可以进行两次查询,在第二次创建COUNT()
并将其加载到您的ExtendedRoot
个实例的代码中。
答案 1 :(得分:0)
班级:
public class RootExtended{
private Root root;
private Long count;
public RootExtended(final Root root, final Long count) {
this.root= root;
this.count= count;
}
// getters and setters to follow
}
查询:
SELECT NEW package.RootExtended ( rt.r, rt.cnt) from ( select r from Root r,
(SELECT count(c.id) as cnt FROM Child c WHERE c.rootId = r.id ) rt )