问题描述
现在我有一个实体对象和一个 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;
}
现在我只能获取存储库以返回列表<对象[] > 类型.
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
这篇关于有没有办法转换弹簧数据存储库返回的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!