4
votes

Right now I have an entity object and a DTO. The repository returns a list of objects arrays when I do a simple example like: findById(). Is there a way to easily map the return type to be a custom DTO object rather than always return entity objects?

Example is below:

@Query("Select f.id, f.name from Food f where f.id = :id")
public List<Object[]> findById(@Param("id") String id);

My DTO object looks like:

FoodDto{
    private String id;
    private String name;
}

Right now I've only ever been able to get repositories to return a List< Object[] > type.

1

1 Answers

20
votes

Try this.

@Query("Select new package.FoodDto(f.id, f.name) from Food f where f.id = :id")
public List<FoodDto> findById(@Param("id") String id);

Assuming class FoodDto is in package, if not you need to set the full package.

Also I assume the FoodDto have a constructor that match

public FoodDto(int id, String name){
 //Variable assignation
}

I never tried in spring-jpa but that works in JPQL so I assume it will work XD