简体   繁体   English

Spring Data JPA - 如何将查询结果转换为实体类

[英]Spring Data JPA - How to convert Query result to entity class

Am using Spring Data JPA with spring boot application.正在将 Spring Data JPA 与 spring boot 应用程序一起使用。 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).考虑到我有 10 个与实体User关联的属性,我只想检索其中的几个(用户名、密码、名字、姓氏、电子邮件)。

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.所以我写了一个查询来只获取 5 个字段,但该方法不返回实体对象,而是返回一个普通对象。

How can I cast the query result to entity in Spring Data JPA ?如何将查询结果转换为 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;
    }
}

and query:并查询:

@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.选择的顺序必须与构造函数的顺序相匹配。

If your Target class is not entity class and you need to parse, Please refer below answer..如果您的 Target 类不是实体类并且您需要解析,请参考以下答案..

ANSWER 回答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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