[英]Map result of a sql query to pojo using spring Data JPA
I am a student learning Spring data jpa.我是一名学习Spring数据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:
我有一个名为 MYDB 的数据库表,其中包含以下字段:
(id, firstname, lastname, rollno, major, country)
And i have an sql query like this:我有一个像这样的 sql 查询:
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.上面的查询返回三个字段:counts(不是 db 列)、last_name 和 major_field。
I have a POJO like this:我有一个这样的 POJO:
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?我的问题是我如何 map 从 sql 查询到我的 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:我被困在这一点上,不知道如何进一步实现对 POJO 的 sql 查询的 map 结果:
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.最终我需要将 MyPojo 转换为 Json object,但我知道该怎么做。 I am only stuck without ideas about assigning result of sql query to pojo.
我只是不知道将 sql 查询的结果分配给 pojo。
Use the javax.persistence @Column
annotation to specify which values from the query are used to populate the fields of the Java object:使用 javax.persistence
@Column
注释指定查询中的哪些值用于填充 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您必须使用 TypedQuery 并提供 class 名称,以便执行查询结果并将其映射到 pojos
Problem solved using interface-based projections:使用基于接口的投影解决的问题:
https://www.baeldung.com/jpa-queries-custom-result-with-aggregation-functions#solution_interface_jpa
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.