How to use Hibernate ResultListTransformer in Spring JPA Repository?

148 Views Asked by At

Vlad Mihalcea describes in How to fetch a one-to-many DTO projection with JPA and Hibernate a use case I want to implement in a Spring Data JpaRepository.

The code in question is the following one:

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();

Is there a way to somehow get this behavior of setting a ResultTransformer in a JpaRepository without directly relying on the EntityManager? I'm looking for something like that:

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

Of course there is no ResultTransformer annotation, the only thing I know that would do something similar is @SqlResultSetMapping, but afaik it ends with Constructor Mapping and is not capable of mapping one-to-many collections.

Is there a way to achieve what I want in an annotation driven approach or do I have to go back to using the EntityManager to benefit from directly result transformed DTO mapping?

1

There are 1 best solutions below

1
jocky4leretour On

You don't need to do anything appart align your JPQL query "AS" with your DTO field's name

See example here https://www.baeldung.com/spring-data-jpa-projections