我的 DTO 结构如下:
public class ADto{
private String name;
private String id;
private List<BDto> bdtos;
//Created constructor using fields
}
public class BDto{
private String id;
private String code;
private List<CDto> cdtos;
//Created constructor using fields
}
public class CDto{
private String mKey;
private String mVal;
//Created constructor using fields
}
使用 Spring MVC 来获取数据。
下面的查询工作得很好并且绑定(bind)了数据:
@org.springframework.data.jpa.repository.Query("select new pkg.ADto(id,name) from AEntity a where a.id=?1")
public ADto getAData(Long id);
如何使用上述方法获取由进一步列表组成的列表的数据?
最佳答案
如果您想在实体上返回 DTO,则需要提供 DTO 和实体之间的映射。对于 JPQL 查询,唯一的选择是在结果对象的构造函数中提供该映射。因此,您需要向 ADto 添加一个接受 BEntities 的构造函数,并将所有嵌套实体映射到该构造函数中的 dtos。或者以更面向对象的方式,新的构造函数将接受 AEntity 作为唯一的参数。
它可能是这样的:
存储库中的 getAData() 方法(通过在结果中添加 a.bEntities 稍微修改 JPQL):
@org.springframework.data.jpa.repository.Query("select new pkg.ADto(id,name, a.bEntities) from AEntity a where a.id=?1")
public ADto getAData(Long id);
ADto 中的新构造函数:
public class ADto{
private String name;
private String id;
private List<BDto> bdtos;
public ADto(String id, String name, List<BEntity> bEntities) {
this.id = id; this.name = name;
this.bdtos = new ArrayList<>();
for (BEntity b : bEntities) {
BDto bdto = new BDto(b.id, b.code, b.cEntities);
/* you need to pass cEntities and map them again in the BDto
* constructor, or you may do the apping in ADto constructor
* and only pass mapped values to BDto constructor */
}
}
}
关于java - JPA 中返回列表类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32784189/