Reputation: 23
Let say I have the following entity, (I skip the constructor for simplicity):
public class Person {
int id;
String name;
String lastName;
Date birthday;
List<Vehicles> vehicles;
}
And I want to create a DTO in order to get only what I need from the DB:
public class PersonDTO {
int id;
String name;
List<Vehicles> vehicles;
}
My Crud repository looks like this:
Person findById(int personId);
But I want to change it to:
PersonDTO findById(int personId);
It works perfectly if I remove the vehicles property, (is a List), but I do need this list. Any clue?
Upvotes: 1
Views: 2079
Reputation: 3373
Citing the Spring Data JPA reference:
Another way of defining projections is by using value type DTOs (Data Transfer Objects) that hold properties for the fields that are supposed to be retrieved. These DTO types can be used in exactly the same way projection interfaces are used, except that no proxying happens and no nested projections can be applied.
Your List<Vehicles> vehicles
is a nested projection, so your apporach is not applicable. You need to make use of an interface-based projection in this case:
public interface PersonProjection {
int getId();
String getName();
List<VehicleProjection> getVehicles();
interface VehicleProjection {
// Getters for desired fields of Vehicle as above for Person(Projection)
}
}
Then you can change your repository method to
PersonProjection findById(int personId);
Unfortunately, the interface-based approach is slightly less performant because, as the reference documentation states, proxying happens.
Upvotes: 2