【问题标题】:JPQL: inner join with group byJPQL:与group by的内部连接
【发布时间】:2013-01-03 22:03:40
【问题描述】:

我正在尝试使用标准构建器从数据库中检索数据。它工作得很好,查询几乎是完美的......几乎。不幸的是,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();

【问题讨论】:

    标签: java mysql jpa criteria-api


    【解决方案1】:

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

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

    【讨论】:

    • 令人惊讶的是它起作用了!显而易见的解决方案是最难看到的;)谢谢!
    猜你喜欢
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    相关资源
    最近更新 更多