【问题标题】:Map Cypher query result to DTO将 Cypher 查询结果映射到 DTO
【发布时间】:2021-12-23 18:39:26
【问题描述】:

我想将密码查询结果映射到 DTO/POJO 类。我在 neo4j 中定义了以下实体:

  1. Products ,具有属性;姓名、职务、地址
  2. 有属性的卖家;姓名,身份证
  3. Listings,有属性;姓名,身份证

关系定义为:产品 -> 卖家和卖家 -> 列表

我的查询结果是Product.Name, [ {Listings.Name, Listings.Id, Sellers.Id, Sellers.Name} ] 的列表。 我希望将其映射到 DTO,但我无法将具有不同节点和标签的结果映射到 DTO/POJO 类。

【问题讨论】:

    标签: java neo4j cypher spring-data-neo4j


    【解决方案1】:

    正如您已经注意到的,Spring Data Neo4j 在映射不直接适用于一个域实体的“任意”数据时更加严格。 但另一方面,Spring Data Neo4j 也支持使用Neo4jClient 映射松散数据。 示例:

    class SoldProductInformation {
       String productName;
       Set<SellingInformation> sellingInformation;
    }
    
    class SellingInformation {
       String listingsName;
       String listingsId;
       String sellerName;
       String sellerId
    }
    
    neo4jClient.query("...return product.name as productName, someListWithTheInformationFromTheQuestion")
      .fetchAs(SoldProductInformation.class)
      .mappedBy((TypeSystem t, Record record) -> {
             String productName = record.get("productName").asString();
             List<SellingInformation> sellingInformations = record.get("someListWithTheInformationFromTheQuestion").asList(value -> {
                 String listingsName = value.get("listingsName").asString();
                 // same for listingsId, sellerName, sellerId...
                 return new SellingInformation(....);
             });
             return new SoldProductInformation(....);
      })
    

    如果您有更多的实体对齐字段和/或可能还返回节点,您可以使用派生映射函数:

    BiFunction<TypeSystem, MapAccessor, Product> mappingFunction = neo4jMappingContext.getRequiredMappingFunctionFor(Product.class);
    

    并通过

    应用它
    neo4jClient.query("...return product,...")
      .fetchAs(SoldProductInformation.class)
      .mappedBy((TypeSystem t, Record record) -> {
          Product product = mappingFunction.apply(typeSystem, record.get("product"));
          String productName = product.getName();
    // ....
    

    有关完整示例,请参阅 https://github.com/spring-projects/spring-data-neo4j/issues/2288#issuecomment-861255508

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 1970-01-01
      • 2019-07-15
      • 2019-07-25
      • 2022-01-11
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多