简体   繁体   English

querydsl从元组获取列

[英]querydsl get column from tuple

I've created query that returns building id and apartments count in that building. 我创建了返回建筑物ID和该建筑物中公寓数量的查询。 How to get buildings with max count from this tuple? 如何从该元组中获得具有最大数量的建筑物? Other than iterate through entire list. 除了遍历整个列表。

JPAQuery<Tuple> query2 = new JPAQuery(entityManager);
QBuildingEntity building = QBuildingEntity.buildingEntity;
QApartmentEntity apartment = QApartmentEntity.apartmentEntity;
query2 = query2.select(apartment.count(), apartment.building.id).from(apartment).where(apartment.status.lower().eq("free"))
                .groupBy(apartment.building);

Here are building and apartment entities: 以下是建筑物和公寓实体:

public class BuildingEntity extends AbstractEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "building", cascade = CascadeType.ALL, orphanRemoval = true)
    Set<ApartmentEntity> apartments = new HashSet<>();
}

public class ApartmentEntity extends AbstractEntity implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;
    @Column(name = "STATUS", nullable = false, length = 50)
    String status;

    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
    @JoinColumn(name = "BUILDING_ID")
    BuildingEntity building;
}

You could order the query by apartment.count() in descending order and pick the first result. 您可以通过apartment.count()降序对查询进行排序,然后选择第一个结果。 Something like: 就像是:

query2.select(apartment.count(), apartment.building.id)
      .from(apartment)
      .where(apartment.status.lower().eq("free"))
      .groupBy(apartment.building)
      .orderBy(apartment.count().desc())
      .limit(1L);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM