Vlad Mihalcea 在如何使用 JPA 和 Hibernate 获取一对多 DTO 投影中描述了我想在 Spring Data 中实现的用例
JpaRepository
。
有问题的代码如下:
List<PostDTO> postDTOs = entityManager.createQuery("""
select p.id as p_id,
p.title as p_title,
pc.id as pc_id,
pc.review as pc_review
from PostComment pc
join pc.post p
order by pc.id
""")
.unwrap(org.hibernate.query.Query.class)
.setResultTransformer(new PostDTOResultTransformer())
.getResultList();
有没有办法以某种方式获得在
ResultTransformer
中设置 JpaRepository
的行为,而不直接依赖于 EntityManager
?我正在寻找类似的东西:
@ResultTransformer(PostDTOResultTransformer.class) /* or any solution that will do the job */
@Query("""
select p.id as p_id,
p.title as p_title,
pc.id as pc_id,
pc.review as pc_review
from PostComment pc
join pc.post p
order by pc.id
""")
List<PostDTO> findAllWithComments();
当然没有
ResultTransformer
注释,我知道唯一能做类似事情的是 @SqlResultSetMapping
,但据我所知,它以 Constructor Mapping 结尾,并且无法映射一对多集合。
有没有办法在注释驱动的方法中实现我想要的目标,或者我是否必须重新使用
EntityManager
才能从直接结果转换的 DTO 映射中受益?
您无需执行任何操作即可将 JPQL 查询“AS”与 DTO 字段名称对齐
请参阅此处的示例https://www.baeldung.com/spring-data-jpa-projections