简体   繁体   中英

Spring Data JPA - How to convert Query result to entity class

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).

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.

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;
    }
}

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..

ANSWER

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