Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 639
R. Pereira Avatar asked Oct 29 '25 11:10

R. Pereira


2 Answers

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.

like image 135
Andronicus Avatar answered Nov 01 '25 03:11

Andronicus


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();
}
like image 42
Greg Avatar answered Nov 01 '25 03:11

Greg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!