简体   繁体   中英

Map result of a sql query to pojo using spring Data JPA

I am a student learning Spring data jpa. I am trying to solve some of practice coding questions. I have a question which i could not find answer to. I have a database table by name MYDB which has fields:

(id, firstname, lastname, rollno, major, country)

And i have an sql query like this:

select Count(*) as counts, lastname as last_name, major as major_field from MYDB group by country

The above query returns three fields: counts(which is not a db column), last_name and major_field.

I have a POJO like this:

public class MyPojo {
    private int counts;
    private String lastName;
    private String majorField;

    // Getters and Setters of all data members here
    ...................
}

My question is how do i map the result that i got from sql query to my POJO? I need to assign:

counts = counts(from sql query), lastName = last_name(from sql query), majorField = major_field(from sql query).

I am stuck at this point and do not know how to implement further to map result of sql query to POJO:

public interface MyRepo extends JpaRepository<MyPojo, String> {
    @Query(value=MY_SQL_QUERY, nativeQuery = true)
    List<MyPojo> findAll();
}

Ultimately i need to convert MyPojo to a Json object, but i know how to do that part. I am only stuck without ideas about assigning result of sql query to pojo.

Use the javax.persistence @Column annotation to specify which values from the query are used to populate the fields of the Java object:

public class MyPojo {

    @Column(name = "counts")
    private int counts;

    @Column(name = "last_name")
    private String lastName;

    ... and so on
}

Here is a great tutorial on the annotations:

You have to use TypedQuery and give your class name for executing and mapping your query result into pojos

Problem solved using interface-based projections:

https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions#solution_interface_jpa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM