Spring Data JPA-如何将查询结果转换为实体类 [英] Spring Data JPA - How to convert Query result to entity class
问题描述
我在Spring Boot应用程序中使用Spring Data JPA.我有一个几乎没有属性的实体类.考虑到我有10个与实体User
关联的属性,我只想检索其中的几个属性(用户名,密码,名字,姓氏,电子邮件).
Am using Spring Data JPA with spring boot application. I have an entity class with few properties. Consider I have 10 properties associated with the entity User
and I want to retrieve only few of them (username,password,firstname,lastname,email).
因此,我编写了一个查询,仅获取5个字段,但是该方法不返回实体对象,而是返回一个普通对象.
So I have wrote a query to get the 5 fields only, but the method does not return entity object, instead it returns a plain object.
如何将查询结果转换为Spring Data JPA中的实体?
How can I cast the query result to entity in Spring Data JPA ?
@Query("select userName,password,firstName,lastName,email from User")
public List<User> getUsers();
推荐答案
您必须创建一个结果类,然后稍稍更改查询:
You have to create a result class and then change the query a bit:
package com.example;
public class ResultClass{
String userName,password,firstName,lastName,email;
public ResultClass(String userName, String password
, String firstName, String lastName, String email){
// set fields;
}
}
并查询:
@Query("select new com.example.ResultClass(userName,password
,firstName,lastName,email) from User")
public List<ResultClass> getUsers();
选择顺序必须与构造函数顺序匹配.
The order of selection must match the constructor ordering.
这篇关于Spring Data JPA-如何将查询结果转换为实体类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!