如何在 JPA Criteria API 上正确使用 JOIN
Posted
技术标签:
【中文标题】如何在 JPA Criteria API 上正确使用 JOIN【英文标题】:How to proper use JOIN on JPA Criteria API 【发布时间】:2021-12-22 19:50:08 【问题描述】:我正在尝试使用 Criteria API 进行动态过滤和 SQL 调节。我的过滤正在工作,但不能执行 join 子句。 这是我的 filter&join 方法。
public Page<ReceivedFax> findAllWithFilters(PageRequest pageRequest,
Map<String, String> receivedFaxSearchCriteriaMap, String uuid)
CriteriaQuery<ReceivedFax> criteriaQuery = criteriaBuilder.createQuery(ReceivedFax.class);
Root<ReceivedFax> receivedFaxRoot = criteriaQuery.from(ReceivedFax.class);
Join<ReceivedFax, Account> join = receivedFaxRoot.join("account");
join.on(criteriaBuilder.equal(join.get("uuid"), uuid));
criteriaQuery.multiselect(join);
Predicate predicate = getPredicate(receivedFaxSearchCriteriaMap, receivedFaxRoot);
criteriaQuery.where(predicate);
TypedQuery<ReceivedFax> typedQuery = entityManager.createQuery(criteriaQuery);
typedQuery.setFirstResult(pageRequest.getPageNumber() * pageRequest.getPageSize());
typedQuery.setMaxResults(pageRequest.getPageSize());
long receivedFaxCount = getReceivedFaxCount(predicate);
return new PageImpl<>(typedQuery.getResultList(), pageRequest, receivedFaxCount);
我需要使用这个 SQL:
select *
from ReceivedFaxes
join Accounts A on A.ID = ReceivedFaxes.AccountID
where A.UUID = '522f6084-893f-4063-92d1-b9130fc88400'(uuid);
我收到此错误:
"org.hibernate.hql.internal.ast.QuerySyntaxException:
Unable to locate appropriate constructor on class [model.receivedfax.ReceivedFax].
Expected arguments are: model.account.Account [
select new model.receivedfax.ReceivedFax(generatedAlias0)
from model.receivedfax.ReceivedFax as generatedAlias1
inner join generatedAlias1.account as generatedAlias0
with generatedAlias0.uuid=:param0 where 1=1];
nested exception is java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException:
Unable to locate appropriate constructor on class [model.receivedfax.ReceivedFax].
Expected arguments are: model.account.Account [
select new model.receivedfax.ReceivedFax(generatedAlias0)
from model.receivedfax.ReceivedFax as generatedAlias1
inner join generatedAlias1.account as generatedAlias0
with generatedAlias0.uuid=:param0 where 1=1]"
【问题讨论】:
你想用这条线做什么? criteriaQuery.multiselect(join);多选是投影 我正在尝试将 Account Entity 加入 ReceivedFax 实体,然后给出 WHERE 子句进行调节。 然后简单地删除 criteriaQuery.multiselect(join); 【参考方案1】:正如西蒙所说,这是我的错。删除后
criteriaQuery.multiselect(join)
Criteria API 正在正常工作。
【讨论】:
以上是关于如何在 JPA Criteria API 上正确使用 JOIN的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 JPA Criteria API 连接不相关的实体
如何在JPA Criteria查询API中编写自定义查询作为根?
JPA 如何获取 Criteria API 中使用的参数标记的数量?