![](/img/trans.png)
[英]Spring Data JPA - Hibernate - OneToMany, ManytoOne bidirectional
[英]Projection in Hibernate/JPA in Spring Boot to pull data from multiple OneToMany and manyToOne relationships
我需要創建一個JPA投影,將拉一切從記錄Entity1
,包括從記錄計數Entity4
。
以下是映射的四個實體及其關系:
Entity1
(ManyToOne) Entity2
(OneToMany) Entity3
(OneToMany) Entity4
在 SQL 中,這可以通過簡單的內聯 select 語句輕松解決。 在 JPA 投影中,我正在嘗試執行以下操作。
@Value("#{target.getEntity2().getEntity3().getEntity4().size()}")
String getEntity4Count();
在上面的這段代碼中,投影在 Entity1 上。 當我添加 Entity4 時它會拋出異常。 下面的代碼有效。
@Value("#{target.getEntity2().getEntity3().size()}")
String getEntity3Count();
這甚至是提取這些數據的正確方法嗎? 所有示例似乎都指向兩個實體之間的關系,這對於非常簡單的應用程序非常有用,但業務應用程序中的 SQL 往往非常復雜。
有沒有辦法用JPQL等另一種方法來完成上面的? 處理需要針對一組實體執行的大量復雜 SQL 的最佳方法是什么?
Spring Data Projections 並不是真正為這種映射制作的,因為它會獲取實體並在@Value
注釋中作為 SPEL(Spring 表達式語言)代碼執行您的“映射”。 我想您更願意使用更高效的 SQL?
這是Blaze-Persistence Entity Views的完美用例。
我創建了該庫以允許在 JPA 模型和自定義接口或抽象類定義的模型之間輕松映射,例如類固醇上的 Spring Data Projections。 這個想法是您按照自己喜歡的方式定義目標結構(域模型),並通過 JPQL 表達式將屬性(getter)映射到實體模型。
使用 Blaze-Persistence Entity-Views 的用例的 DTO 模型可能如下所示:
@EntityView(Entity1.class)
public interface Entity1Dto {
@IdMapping
Long getId();
@Mapping("COUNT(entity2.entity3.entity4)")
Long getCount();
}
查詢是將實體視圖應用於查詢的問題,最簡單的只是按 id 查詢。
Entity1Dto a = entityViewManager.find(entityManager, Entity1Dto.class, id);
Spring Data 集成允許您像使用 Spring Data Projections 一樣使用它: https : //persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.