简体   繁体   中英

How to fetch Self Referencing object in GET call using Spring Data Rest

I am using Spring 1.3.3 and I am unable to get Self Referencing object in the Spring Data Rest Response using GET even if it is not null.

eg

My Table:

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

Response:

{
"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"
}
}
}

But I need the parent_id next to the name field instead of under " links ".

  1. Is there a way to return the parentId in the Employee object (next to the name) ?

OR

  1. Should I need to add the projection to return the self referencing object?

I would suggest to use jackson on top of your spring rest. You can then easily add an annotation to the domain object to rename links to parent_id.

 @JsonProperty("parent_id")

You also need to add two annotations above the class

@JsonSerialize
@JsonInclude

Best practice actually is not to use the domain object directly but to use a pojo in between which is dealing with this. So then the domain object data will be copied to that pojo and you will only show what you want to show in the rest response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM