我有两个实体:如何在Spring Data中进行“按聚合函数排序”?
的resourcefile:
@Entity
@Table(name = "resource_file")
public class ResourceFile extends IdEntity<Integer> {
@Id
@SequenceGenerator(name = "resource_file_id_generator", sequenceName = "resource_file_id", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "resource_file_id_generator")
@Column(name = "id", unique = true, nullable = false)
@Nonnegative
private Integer id;
...
}
FavoriteResourceFile:
@Entity
@Table(name = "favorite_resource_file")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class FavoriteResourceFile extends IdEntity<FavoriteResourceFileId> {
@EmbeddedId
private FavoriteResourceFileId id;
@MapsId("resourceFileId")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "resource_file_id", nullable = false)
private ResourceFile resourceFile;
...
}
我想使下面的查询“选择所有的资源文件,并通过最喜欢的资源文件的数量进行排序”。
在SQL它看起来像:
select rf.id, count(frf.resource_file_id) from resource_file rf
left join favorite_resource_file frf on frf.resource_file_id = rf.id
group by rf.id
order by count(rf.id) desc;
但我不知道如何与Spring数据,以及如何做到这一点,使映射到实体的resourcefile在最后。
一些限制:
- 我不能让有关FavoriteResourceFile中的resourcefile, 因为它们位于不同的模块
- 我不想使用本地SQL或JPA查询(如字符串)。
- 最好使用元模型,规范或QueryDSL,因为它们已经在项目中使用。
有人可以帮我吗?