@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?
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.
I found two solutions:
1. Using a class to convert:
@Query("SELECT new com.example.project.TestPojo(tt, at.field, at.anotherField) from TableTest tt LEFT JOIN AnotherTable at ON at.commonField = tt.commonField")
List<TestPojo> findAllPojo(List<TableTestDTO> TableTestDTOList);
Class:
package com.example.project;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class TestPojo {
private Long tt;
private String field;
private String anotherField;
}
2. Using an interface to convert:
@Query("SELECT tt AS tt, at.field AS field, at.anotherField AS anotherField from TableTest tt LEFT JOIN AnotherTable at ON at.commonField = tt.commonField")
List<TestPojo> findAllPojo(List<TableTestDTO> TableTestDTOList);
Interface:
public interface TestPojo {
Long getTt();
String getField();
String getAnotherField();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With