Java 如何制作;“按聚合函数排序”;春季数据?

Java 如何制作;“按聚合函数排序”;春季数据?,java,spring,jpa,spring-data,spring-data-jpa,Java,Spring,Jpa,Spring Data,Spring Data Jpa,我有两个实体: 资源文件: @Entity @Table(name = "resource_file") public class ResourceFile extends IdEntity<Integer> { @Id @SequenceGenerator(name = "resource_file_id_generator", sequenceName = "resource_file_id", allocationSize = 1) @Generate

我有两个实体:

资源文件:

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

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

    ...

}
但我不明白如何使用Spring数据以及如何在最后映射到ResourceFile实体

一些限制:

  • 我无法在ResourceFile中建立与FavoriteResourceFile的关系, 因为它们位于不同的模块中
  • 我不想使用本机SQL或JPA查询(作为字符串)
  • 最好使用元模型、规范或QueryDSL,因为它们已经在项目中使用了

有人能帮我吗?

您可以使用自定义存储库实现以及Crud/分页和排序存储库实现,如下所示:

终点回购:

公共接口ResourceFileRepository扩展
分页和排序存储库,
ResourceFileRepositoryCustom{
}
定制回购:

公共接口ResourceFileRepositoryCustom{
列出GetResourceFilesOrderByFavorites();
}
自定义repo实现,使用实际代码检索按收藏夹计数排序的ResourceFile(请注意,它是ResourceFileRepositoryImpl,而不是ResourceFileRepositoryCustomImpl)

我没有那些嵌入的键,所以我不得不简化一点。 查询来自FavoriteResourceFile,因为ResourceFile与FavoriteResourceFile没有自己的关系

公共类ResourceFileRepositoryImpl实现ResourceFileRepositoryCustom{
@持久上下文
私人实体管理者;
公共无效设置EntityManager(EntityManager em){
this.em=em;
}
@凌驾
公共列表GetResourceFileOrderByFavorites(){
CriteriaBuilder CriteriaBuilder=this.em.getCriteriaBuilder();
CriteriaQuery q=criteriaBuilder
.createQuery(ResourceFile.class);
Root=q.from(FavoriteResourceFile.class);
Join=root.Join(
FavoriteResourceFile_u2;.resourceFile,JoinType.LEFT);
q、 选择(加入);
q、 groupBy(join.get(ResourceFile.id));
q、 orderBy(criteriaBuilder.desc(
Criteria.count(
join.get(ResourceFile.id));
TypedQuery=this.em.createQuery(q);
返回query.getResultList();
}
}
要查看完整的示例项目(使用一些非常基本的sql和测试)-checkout/fork/etc:

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;
public interface ResourceFileRepositoryCustom {
    List<ResourceFile> getResourceFilesOrderByFavourites();
}