Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带subselect的JPA查询_Jpa - Fatal编程技术网

带subselect的JPA查询

带subselect的JPA查询,jpa,Jpa,我想提出以下问题 select * from( select pI, max(pAs) as pAs from mytable and pAs>=?1 and pAs<=?2 and pI like 'DE%%' and pE like ?6 group by pI ) as x inner join mytable

我想提出以下问题

select * from(
            select pI, max(pAs) as pAs from mytable
            and pAs>=?1 and pAs<=?2
            and pI like 'DE%%'
            and pE like ?6
            group by pI
            ) as x
            inner join mytable as a
            on a.pI=x.pI
            and a.pAs=x.pAs
使用hibernate中的criteriabuilder。我没有成功,到目前为止使用了nativeQuery

然而,我无法解决的问题的关键似乎是,我需要在subselect中返回两个属性。我找到的所有示例只返回一个属性

这真的是jpa/hibernate的一个限制,还是有一种方法可以实现我想要的?
非常感谢您的帮助/指点。

您没有提供有关您的实体的任何信息。所以我怀疑您有Mytable实体类,它有长字段


首先,您需要实体当SQL语句执行您需要的操作时,为什么要使用CriteriaAPIwant@alexvaluiskyi我确实有一个用于最终查询的实体。拥有临时实体是否允许我从子选择返回多个属性?您是否碰巧有一个工作示例?是否要获取子选择属性作为查询结果?或者你只需要在子句中使用它吗?@alexvaluiskyi在这种情况下,我真的只需要在自连接中使用它们。
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Mytable> query = builder.createQuery(Mytable.class);
Root<Mytable> root = query.from(Mytable.class);

Subquery<Long> subquery = query.subquery(Long.class); // max(pAs)
Root<Mytable> subRoot = subquery.from(Mytable.class);

Predicate predicate1 = 
         builder.equal(root.get("pI"), subRoot.get("pI"));

Predicate predicate2 = 
         builder.greaterThan(subRoot.get("pAs"), 0);

Predicate predicate3 = 
         builder.lessThan(subRoot.get("pAs"), 100);

//There is a simple example. But you can add as many predicates as you need
Predicate fullPredicate = 
         builder.and(predicate1, predicate2, predicate3);

Predicate havingPredicate = 
         builder.equal(root.get("pAs"), builder.max(subRoot.get("pAs")));

subquery.select(builder.max(subRoot.get("pAs"))).where(fullPredicate)
    .groupBy(subRoot.get("pI")).having(havingPredicate);

query.select(root).where(builder.exists(subquery));

List<Mytable> result = entityManager.createQuery(query).getResultList();