2

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
  • I am not sure how this is relevant, if you are using it within the code then doesn't matter. But if you want to return it to front end, then you must never use Model classes directly. Refer this Entity to DTO conversion for reference. Commented Feb 15, 2021 at 12:10
  • You can just simple call for your required fields of the object. Commented Feb 15, 2021 at 12:32

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

5 Comments

Okay, thank you! Where do I add the interface ? Into the class Person?
@user3476509 wherever you want. I would prefer placing it near relevant Repository classes
I got the error: Could not write JSON: Failed to convert from type [java.lang.String] to type [long]
@user3476509 try to use Long instead of long. Though I don't get why it's even being converted in JSON
@user3476509 if it's solved you can Accept my answer
2

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.

2 Comments

I would like to return the object Person, but with just the attributes id and email.
If you handle an instance of Person it always has all of the fields. Whether these fields actually contain useful information is another matter. But you cannot strip fields from a class. See Nikolai's answer for an approach using a different structure.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.