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

自古美人都是妖i 提交于 2019-12-12 10:46:49

问题


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();

回答1:


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.



来源:https://stackoverflow.com/questions/47471384/spring-data-jpa-how-to-convert-query-result-to-entity-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!