[英]How to Use JPA map native query into nested projection
我有兩個表,用戶和角色,它們是多對多的
它們也是大表,不要期望所有不相關的列返回。
所以我有本機查詢,(並且必須使用本機)。
select u.name, r.name, r.uuid
from user u
join user_role_join urj on urj.user_uuid = u.uuid
join role r on r.uuid = urj.role_uuid;
從返回開始,一個用戶顯示多個角色。
Adam | superAdmin | {uuid1}
Adam | admin | {uuid2}
Lisa | guest | {uuid3}
...
我需要回報以適應 pojo
User
String name,
List<Role> roles;
Role
String name,
UUID uuid
我正在使用 EntityManager 進行查詢。
我怎樣才能讓 JPA 知道 map 一個具有多個角色的用戶?
{
name:Adam
roles:[
{
uuid:{uuid1}
name:superAdmin
},
{
uuid:{uuid2}
name:admin
}
]
},
{
name:Lisa
roles:[
{
uuid:{uuid3}
name:guest
}
]
}
我不知道為什么你需要使用原生查詢,但是當涉及到 collections 時,JPA/Hibernate 只能在使用實體時幫助你。
如果您想避免不必要的 select 項,我建議您嘗試使用 JPA model 和 Blaze-Persistence,因為這是Blaze-Persistence 實體視圖的完美用例。
我創建了庫以允許在 JPA 模型和自定義接口之間輕松映射或抽象 class 定義的模型,類似於類固醇上的 Spring 數據投影。 這個想法是,您按照自己喜歡的方式定義目標結構(域模型),並通過 JPQL 表達式將 map 屬性(getter)定義為實體 model。
對於您的用例,DTO model 對於 Blaze-Persistence 實體視圖可能如下所示:
@EntityView(User.class)
public interface UserDto {
@IdMapping
UUID getId();
String getName();
Set<RoleDto> getRoles();
@EntityView(Role.class)
interface RoleDto {
@IdMapping
UUID getUuid();
String getName();
}
}
查詢是將實體視圖應用於查詢的問題,最簡單的就是通過 id 進行查詢。
UserDto a = entityViewManager.find(entityManager, UserDto.class, id);
Spring 數據集成允許您幾乎像 Spring 數據投影一樣使用它: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.