首页 > 解决方案 > querydsl 从元组中获取列

问题描述

我创建了返回该建筑物中的建筑物 ID 和公寓计数的查询。如何从此元组中获得最大数量的建筑物?除了遍历整个列表。

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);

以下是建筑和公寓实体:

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;
}

标签: javaquerydsl

解决方案


您可以按apartment.count()降序排列查询并选择第一个结果。就像是:

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

推荐阅读