querydsl从元组中获取列

时间:2018-08-26 17:11:14

标签: java 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;
}

1 个答案:

答案 0 :(得分:0)

您可以按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);