【问题标题】:QueryDSL JPA- Self join without relationship with group byQueryDSL JPA- 与 group by 没有关系的自加入
【发布时间】:2015-12-29 19:30:07
【问题描述】:

有什么方法可以使用 QueryDSL 获取此查询?

select
  person.name,
  count(neighbors.*)
from person as neighbors
where person.address = neighbor.address
group by person.name

address 不是 FK。

【问题讨论】:

    标签: java jpa jpql querydsl


    【解决方案1】:

    第一个问题的关键是使用别名来进行自连接:

    // static instance uses default alias "person"
    QPerson person = QPerson.person;
    QPerson neighbor = new QPerson("neighbor");
    
    JPAQuery query = new JPAQuery(em)
        .from(person, neighbor)
        .where(person.adress.eq(neighbor.adress))
        .groupBy(person.name);
    

    要获得结果,您可以简单地使用 Tuple 类:

    List<Tuple> results = query.list(person.name, neighbor.count());
    for (Tuple row : result) {
        System.out.println("name: " + row.get(person.name));
        System.out.println("count: " + row.get(neighbor.count()));
    }
    

    或者你可以使用ConstructorExpression 来做这样的事情:

    List<MyResult> results = query.list(ConstructorExpression.create(
            MyResult.class, person.name, neighbor.count()));
    
    public class MyResult {
        private String name;
        private long count;
        public MyResult(String name, long count) {
            this.name = name;
            this.count = count;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      • 2021-07-15
      相关资源
      最近更新 更多