【问题标题】:How to fetch Self Referencing object in GET call using Spring Data Rest如何使用 Spring Data Rest 在 GET 调用中获取自引用对象
【发布时间】:2016-11-29 07:10:03
【问题描述】:

我使用的是 Spring 1.3.3,我无法使用 GET 在 Spring Data Rest Response 中获取自引用对象,即使它不为空。

例如

我的桌子:

CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(40) NOT NULL,
  `parent_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  KEY `FK_employee_parent` (`parent_id`),
  CONSTRAINT `FK_employee_parent` FOREIGN KEY (`parent_id`) REFERENCES `employee` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8057 DEFAULT CHARSET=latin1

回复:

{
"id": 1,
"name": "Test Employee",
"_links": {
"self": {
"href": "http://localhost:8081/employee/1"
},
"employee": {
"href": "http://localhost:8081/employee/1"
},
"parent": {
"href": "http://localhost:8081/employee/1/parent"
}
}
}

但我需要在名称字段旁边而不是在“链接”下的 parent_id。

  1. 有没有办法在Employee对象中返回parentId(下一个 名字)?

  1. 是否需要添加投影才能返回 自引用对象?

【问题讨论】:

  • 是的,您可以使用投影来内联有关正文中关联的一些信息。

标签: java spring-boot spring-data-rest


【解决方案1】:

我建议在弹簧架上使用 jackson。然后,您可以轻松地向域对象添加注释,以将链接重命名为 parent_id。

 @JsonProperty("parent_id")

你还需要在类上面添加两个注解

@JsonSerialize
@JsonInclude

最佳实践实际上不是直接使用域对象,而是使用一个 pojo 来处理这个问题。因此,域对象数据将被复制到该 pojo 中,您将只显示您想在其余响应中显示的内容。

【讨论】:

  • 这是一个关于 Spring Data Rest 的问题。它使用实体。
猜你喜欢
  • 2021-05-15
  • 1970-01-01
  • 2014-05-22
  • 2014-03-18
  • 2014-12-05
  • 1970-01-01
  • 2020-04-22
  • 1970-01-01
  • 2018-03-10
相关资源
最近更新 更多