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;
}
解决方案
您可以按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);
推荐阅读
- mongoexport - 使用 mongoexport 从特定时间范围内使用查询和时间戳从 mongodb 导出数据
- html - 在相同大小的单元格中显示具有不同高度和宽度的图像
- angular - 单角反应形式的两个独立验证
- javascript - 网络元素突然消失
- macos - Zsh 外壳别名
- mongodb - 更新对象数组中的字段
- angular - 尝试在 Angular 中执行删除操作时出错
- android - 为什么在“空中”创建的锚点在 ARCore 中不是静态的
- c++ - 可以构造一个空的 std::optional
调用 T 的默认构造函数? - c++ - 是否有理由在 C++ 中转发声明 main