有没有一种方法可以转换弹簧数据存储库返回的对象? [英] Is there a way to transform objects that spring data repositories return?
问题描述
现在我有一个实体对象和一个DTO.当我做一个简单的示例(如findById())时,存储库将返回对象数组的列表.有没有一种方法可以轻松地将返回类型映射为自定义DTO对象,而不是始终返回实体对象?
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?
示例如下:
@Query("Select f.id, f.name from Food f where f.id = :id")
public List<Object[]> findById(@Param("id") String id);
我的DTO对象看起来像:
My DTO object looks like:
FoodDto{
private String id;
private String name;
}
现在,我只能获取存储库以返回List<对象[]>类型.
Right now I've only ever been able to get repositories to return a List< Object[] > type.
推荐答案
尝试一下.
@Query("Select new package.FoodDto(f.id, f.name) from Food f where f.id = :id")
public List<FoodDto> findById(@Param("id") String id);
假设FoodDto类位于包装中,如果没有,则需要设置完整的包装.
Assuming class FoodDto is in package, if not you need to set the full package.
我还假设FoodD具有匹配的构造函数
Also I assume the FoodDto have a constructor that match
public FoodDto(int id, String name){
//Variable assignation
}
我从没在spring-jpa中尝试过,但是在JPQL中可以使用,所以我认为它可以在XD中使用
I never tried in spring-jpa but that works in JPQL so I assume it will work XD
这篇关于有没有一种方法可以转换弹簧数据存储库返回的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!