Search code examples
javaspringspring-bootapidao

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


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 ?


Solution

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