JPQL:与group by的内部联接

时间:2013-01-20 20:00:05

标签: java mysql jpa criteria-api

我正在尝试使用criteriabuilder从数据库中检索数据。它工作得很好,查询几乎是完美的......差不多。不幸的是,Java不希望我使用group by或distinct作为查询的结果。如何使Java只检索唯一的记录?我的代码在这里:

List<Documentation> documentationList = new ArrayList<>();
DatabaseConnector dc = new DatabaseConnector();
List<Predicate> criteria = new ArrayList<Predicate>();
EntityManager em = dc.getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();

CriteriaQuery<Documentation> select = builder.createQuery(Documentation.class);
Root<Documentation> u = select.from(Documentation.class);
Join<Documentation, DocumentationUser> du = u.join("documentationUserCollection",     JoinType.INNER);

javax.persistence.Query q = em.createQuery(select);
select.groupBy(u.<String>get("documentationId"));
select.distinct(true);

documentationList = q.setMaxResults(pageSize).setFirstResult(first).getResultList();

1 个答案:

答案 0 :(得分:2)

尝试在创建查询的行下方交换2行:

select.groupBy(u.<String>get("documentationId"));
select.distinct(true);

javax.persistence.Query q = em.createQuery(select);