3

我正在编写一些代码,这些代码使用 spring-data-neo4j (SDN) 和 spring-data-rest-mvc 来存储和访问具有循环特征的图形数据。我正在使用 spring-data-rest-mvc 来访问 HATEOAS 功能,以允许客户端通过链接来导航图表。

作为一个简单的例子,我从http://spring.io/guides/gs/accessing-neo4j-data-rest/获取了 gs-accessing-neo4j-data-rest 代码,并用一种​​增强了 Person 类社交方面,即“朋友”为:

@RelatedTo(type = "FRIENDS_WITH", direction = Direction.BOTH)
Set<Person> friends = new HashSet<Person>();

即 Person 实例之间的双向关系。

我加载了一组样本数据,并在它们之间建立了随机的朋友关系。到目前为止一切都很好。

如果我打

http://localhost:8080/people/408 

我得到了预期:

{
  "firstName" : "Remona",
  "lastName" : "Heier",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/people/408"
    },
    "friends" : {
      "href" : "http://localhost:8080/people/408/friends"
    }
  }
}

如果我打

http://localhost:8080/people/408/friends

但是,我得到

{
  "_embedded" : {
    "people" : [ {
      "firstName" : null,
      "lastName" : null,
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/people/189"
        },
        "friends" : {
          "href" : "http://localhost:8080/people/189/friends"
        }
      }
    }, {
      "firstName" : null,
      "lastName" : null,
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/people/34"
        },
        "friends" : {
          "href" : "http://localhost:8080/people/34/friends"
        }
      }
    }
  }
}

其中包含 firstName 和 lastName 的空值。

直接打其中一个朋友,例如

http://localhost:8080/people/189

我得到:

{
  "firstName" : "Zita",
  "lastName" : "Speltz",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/people/189"
    },
    "friends" : {
      "href" : "http://localhost:8080/people/189/friends"
    }
  }
}

我明白为什么我得到空值 - 朋友集上没有 @Fetch,所以实际上并没有获取朋友 - 只有节点 ID 是已知的,用于构建自我和朋友的 href。但是使用空值产生的输出是错误的——这是对数据的错误表述。

我不能在朋友集中包含@Fetch,因为这会使应用程序进入旋转并溢出堆栈,所以这就是我被卡住的地方。我想查看列出好友时显示的好友的非关系属性,即我想查看:

{
  "_embedded" : {
    "people" : [ {
      "firstName" : "Zita",
      "lastName" : "Speltz",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/people/189"
        },
        "friends" : {
          "href" : "http://localhost:8080/people/189/friends"
        }
      }
    }, {
      "firstName" : "Ciara",
      "lastName" : "Cobbley",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/people/34"
        },
        "friends" : {
          "href" : "http://localhost:8080/people/34/friends"
        }
      }
    }
  }
}

有谁知道我怎么能做到这一点?

提前谢谢了。

4

1 回答 1

1

这似乎是 spring-data 或 spring-data-rest 中的错误。我在使用 spring-data-rest 2.3.0 和 spring-data-jpa 的延迟获取的实体上遇到了同样的事情。我能够获得您想要的输出(即实际显示的实体信息)的唯一方法是急切地获取相关实体。你说你不能这样做,所以我看到的唯一选择是让你编写自己的控制器来返回正确的数据。您只需要覆盖引用实体的 requestMappings,因为 spring-data-rest 控制器仍将处理您的控制器未处理的任何 requestMappings。spring-restbucks 项目在这里有一个自定义控制器的示例:

https://github.com/olivergierke/spring-restbucks/blob/master/src/main/java/org/springsource/restbucks/payment/web/PaymentController.java

您需要添加一个方法来处理“/people/{id}/friends”请求映射,并使用数据和链接自己填充资源。

于 2015-03-30T16:45:24.000 回答