【发布时间】:2012-11-20 02:19:20
【问题描述】:
我有两个实体:
资源文件:
@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;
...
}
我想进行以下查询“选择所有资源文件并按最喜欢的资源文件的数量对其进行排序”。
在 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 Data 进行操作,以及最后如何映射到 ResourceFile 实体。
一些限制:
- 我无法在 ResourceFile 中与 FavoriteResourceFile 建立关系, 因为它们位于不同的模块中
- 我不想使用原生 SQL 或 JPA 查询(作为字符串)。
- 最好使用元模型、规范或 QueryDSL,因为它们已在项目中使用。
有人可以帮我吗?
【问题讨论】:
标签: java spring jpa spring-data spring-data-jpa