java - JPA 中返回列表类型

标签 java spring jpa

我的 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/

相关文章:

java - 为什么会延迟生成 Java String 哈希码?

java - Maven 肯定火 : Running tests in specified dependencies

java - 为什么我的 JTable CellRenderer 一直在运行?

java - 直接来自存储库的 @NamedQuery 元素上的错误

gwt - 了解 Spring Roo 为 GWT 生成的实体代码

java - Jackson 中的多态反序列化基于整数,而不是字符串

java - Spring MVC JPA 异常 org.hibernate.exception.SQLGrammarException

spring - 如何在 Websphere ND 8.5 中运行 Spring Batch 管理

Java : Send Multipart File to RESTWebservice

java - QueryDSL:QueryDSL 2.9.0 中 ConstructorExpression 和 CaseBuilder 的 JPA 示例