连接同一列的值

时间:2016-10-31 11:01:27

标签: java jpa

我用条件查询编写了以下代码:

    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> cq = criteriaBuilder.createTupleQuery();

    Root root = cq.from(Offer.class);
    Join recipients = root.join("recipients", JoinType.LEFT);
    Join items = recipients.join("items", JoinType.LEFT);
    Join category = items.join("category", JoinType.LEFT);
    Join superCategory = category.join("superCategory", JoinType.LEFT);

    cq.select(criteriaBuilder.tuple(
            root.get("id").alias("id"),
            criteriaBuilder.concat(
                    criteriaBuilder.concat(superCategory.get("name"), ": "),
                    criteriaBuilder.concat(items.get("item"), ", ")).alias("item")
    ));
    cq.distinct(true);
    cq.where(criteriaBuilder.isNotNull(items.get("item")));
    cq.orderBy(criteriaBuilder.asc(root.get("id")));
    List<Tuple> itemsResultList = entityManager.createQuery(cq).getResultList();

此查询产生以下结果:

Id  | Item
----------------
1   | C1: Apple,        
1   | C2: Book,
1   | C3: Phone,
2   | C2: Book,
2   | C4: Pizza,
3   | C1: Apple,
5   | C3: Phone,
5   | C5: Car,
5   | C6: Tee, 
5   | C1: Apple,

我想要的是获得以下结果:

Id  | Item
-------------------------------------
1   | C1: Apple, C2: Book, C3: Phone,
2   | C2: Book, C4: Pizza,
3   | C1: Apple,
5   | C3: Phone, C5: Car, C6: Tee, C1: Apple,

如何聚合和连接同一列的值(如上所示)?

0 个答案:

没有答案