简体   繁体   中英

Embedding a link using Spring HATEOAS

I have link accessible data in my JSON files now. I have Account.class (Account.java, resource, assembler, controller, embeddable etc..) and same for Post.class. However, I would like to embed the author of the post in the database record for that post. Right now I have this:

    "embeddeds": null,
    "content": "New content",
    "time": "18.00",
    "gender": null,
    "age": null,
    "_links": {
      "self": {
        "href": "http://localhost:8080/posts/570faae01bdbea94f8c79307"
      }
    }

I want to have something like this:

"content": "New content",
"time": "18.00",
"gender": null,
"age": null,
"id": "570faae01bdbea94f8c79307",
"_links": {
  "self": {
    "href": "http://localhost:8080/posts/570faae01bdbea94f8c79307"
  },
  "post": {
    "href": "http://localhost:8080/posts/570faae01bdbea94f8c79307"
  }
  "madeBy": {
    "href": "http://localhost:8080/accounts/someId"
}

How do I implement this? I need to embed the link of the account that made this post into the post itself. Do I have to include the account in the POST controller or do I have to adjust something in the embeddables? I don't know where to start.

Your Post class should contain a reference to the author's Account .

Both Post and Account class have an endpoint representing them (controller annotated with @ExposesResourceFor(Post.class) etc..) and a ResourceAssembler implementing linkToSingleResource(...) .

You may have a look at this sample project: https://github.com/opencredo/spring-hateoas-sample and to the related post: Implementing HAL hypermedia REST API using Spring HATEOAS

In this project Author , Book and Publisher class are related, and endpoints generate the _link for all of them.

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