Search code examples
javaspringspring-data-jpapojo

How to map JPA query results to a POJO?


@Query("SELECT tt, at.field, at.anotherField from TableTest tt LEFT JOIN AnotherTable at ON at.commonField = tt.commonField")
List<TestPojo> findAllPojo(List<TableTestDTO> TableTestDTOList);

How can I map this JPA query results to a Pojo without native query, like this approach ?

I'm using JPA and Hibernate. Can anyone provide other option?


Solution

  • Try using the constructor:

    @Query("SELECT new TestPojo(tt, at.field, at.anotherField) from TableTest tt LEFT JOIN AnotherTable at ON at.commonField = tt.commonField")
    List<TestPojo> findAllPojo(List<TableTestDTO> TableTestDTOList);
    

    Of course such constructor must exist and even better would be to place the fully qualified name instead of bare TestPojo.