How to return specific object attributes in spring boot queries with DAO?

Viewed 1114

in my Spring Boot application I have an entity called Person.class, which contains

long id;
String email;
String name;
String surname;
String address;

In the DAO class, I have a method:

List<Person> findAllByEmail(String email);

Which queries the Database and returns a list of Person.

I would like to return a list of Person with just some attributes, for example:

long id;
String email;

Without return the entire object.

This would be equivalent to execute the query:

"select id, email from person where email = ?"

But I would like to maintain the function query into the DAO as

List<Person> findAllByEmail(String email);

Without writing the queries by hand.

How can I do it ?

2 Answers

Returning multiple values from a method is not possible. In your calling method, when iterating over the returned List<Person>, you should read the required fields from each Person out of the List into local variables and work with those.

You can use JPA Projections

  1. Create interface with getters of desired columns
interface WithIdAndEmail {
   long getId();
   String getEmail();
}
  1. Use that interface as the return type of the method
List<WithIdAndEmail> findAllByEmail(String email);
Related