我对 JPA 比较陌生,它是 CriteriaBuilder / CriteriaQuery API:
我想查询一组对象的提取(如下所示,我只选择元素 n 到 m 的结果)
查询本身运行良好,我得到了我期望的结果。
但是如果我尝试计算全部可能的结果,我会得到一个 java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException: 无效路径: 'generatedAlias1.prop1' [从 com.myCompany.blablub.MyClass 中选择 count(generatedAlias0) as generatedAlias0 where (1=1) and (generatedAlias1.prop1=:param0) )]"
final CriteriaQuery<MyClass> criteriaQuery = builder.createQuery(MyClass.class);
CriteriaQuery<Long> countQuery = builder.createQuery(Long.class);
countQuery.select(builder.count(countQuery.from(MyClass.class)));
Long totalCount = -1L;
List<MyClass> MyClassList;
Root<MyClass> root = criteriaQuery.from(MyClass.class);
if(myClassFilter != null) {
List<Predicate> predicates = new ArrayList<Predicate>();
if(myClassFilter.getProp1() != null) {
Join<MyClass, MyOtherClass> myJoin1 = root.join(MyClass_.prop1);
predicates.add(builder.equal(myJoin1.get(MyOtherClass_.blah), myClassFilter.getProp1() ));
}
if(myClassFilter.getProp2() != null) {
predicates.add(builder.equal(root.get(MyClass_.blubb), myClassFilter.getProp2() ));
}
if(myClassFilter.getProp3() != null) {
Join<MyClass, MyOtherClass> myJoin2 = root.join(MyClass_.foo);
predicates.add(builder.equal(myJoin2.get(MyOtherClass_.bar), myClassFilter.getProp3() ));
}
if (myClassFilter.getSpecialPropList() != null) {
if (myClassFilter.getSpecialPropList().length>0) {
Predicate orPredicates = builder.disjunction();
for (String specialProp : myClassFilter.getSpecialPropList()) {
Join<MyClass, specialProp> specialPropJoin = root.join(MyClass_.specialProps);
Predicate newPredicate = builder.equal(specialPropJoin.get(specialProp_.dudum), specialProp);
orPredicates = builder.or(orPredicates, newPredicate);
}
predicates.add(orPredicates);
}
}
Predicate finalPredicate = builder.conjunction();
for(Predicate p: predicates) {
finalPredicate = builder.and(finalPredicate, p);
}
criteriaQuery.select(root).where(finalPredicate);
countQuery.where(finalPredicate);
}
count = entityManager.createQuery(countQuery).getFirstResult();
TypedQuery<MyClass> typedQuery = entityManager.createQuery(criteriaQuery);
if(first >= 0) {
typedQuery.setFirstResult(first);
}
if(count > 0) {
typedQuery.setMaxResults(count);
}
MyClassList = typedQuery.getResultList();
我希望你能给我一个提示我做错了什么。
我想我明白我的问题出在哪里了。
该行为仅在我使用联接时出现。
没有连接的查询如下所示:
select count(generatedAlias0) from MyClass as generatedAlias0 where ( 1=1 ) and ( generatedAlias0.blubb=:param0 )
但是当我想使用连接时,它看起来像这样:
select count(generatedAlias0) from MyClass as generatedAlias0 where ( 1=1 ) and ( generatedAlias1.blah=:param0 )
而没有计数的查询看起来像这样:
select generatedAlias0 from MyClass as generatedAlias0 inner join generatedAlias0.prop1 as generatedAlias1 where ( 1=1 ) and ( generatedAlias1.blah=:param0 )
它显然不知道 generatedAlias1 是什么,因为整个连接都丢失了。有谁知道我该如何解决这种行为?