Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simply add a link to a Spring Data REST Entity

I have my Entities with Spring Data JPA, but to generate stats about them, I use jOOQ in a Spring @Repository.

Since my methods return either a List of entities, or a Double, how can I expose them as links? Let's say I have a User entity, I want to get the following JSON:

{
  "_embedded" : {
    "users" : [ ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/api/users"
    },
    "stats" : {
      "href" : "http://localhost:8080/api/users/stats"
    }
    "profile" : {
      "href" : "http://localhost:8080/api/profile/users"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 0,
    "totalPages" : 0,
    "number" : 0
  }
} 

And in http://localhost:8080/api/users/stats I want to get a list of links with the methods I declared in my jOOQ repository. How would I approach this? Thanks.

like image 285
Desiderantes Avatar asked Dec 15 '15 15:12

Desiderantes


People also ask

What is the use of spring Hateoas?

Spring HATEOAS provides some APIs to ease creating REST representations that follow the HATEOAS principle when working with Spring and especially Spring MVC. The core problem it tries to address is link creation and representation assembly.

What is used for exposing spring data repositories over rest using Spring Data rest?

It is called spring-boot-starter-data-rest. This package makes it extremely easy to build hypermedia-based RESTful APIs. These APIs directly connect to the Spring Data repositories. Also, Spring automatically adds hypermedia capabilities to the exposed end-points.

What is Data rest in spring?

Spring Data REST builds on top of Spring Data repositories, analyzes your application's domain model and exposes hypermedia-driven HTTP resources for aggregates contained in the model.


1 Answers

https://docs.spring.io/spring-hateoas/docs/current/reference/html/#reference

    public class PaymentProcessor implements RepresentationModelProcessor<EntityModel<Order>> {
        @Override
        public EntityModel<Order> process(EntityModel<Order> model) {
            model.add(
                    Link.of("/payments/{orderId}").withRel(LinkRelation.of("payments")) //
                            .expand(model.getContent().getOrderId()));
            return model;
        }
    }

migrate-to-1.0.changes

ResourceSupport is now RepresentationModel

Resource is now EntityModel

Resources is now CollectionModel

PagedResources is now PagedModel

like image 56
kyakya Avatar answered Sep 29 '22 16:09

kyakya