Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to transform objects that spring data repositories return?

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.

like image 689
user1099123 Avatar asked Nov 30 '22 02:11

user1099123


1 Answers

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

like image 186
Koitoer Avatar answered Dec 15 '22 04:12

Koitoer