Search code examples
javaspringrestspring-dataspring-data-rest

RestResource: get id of subentity without extra request


I have entities like this:

@Entity
class MyEntity {
    Long id;
    SecondEntity second;
    ...
}

@Entity
class SecondEntity {
    Long id;
    ...
}

I use @RestResource for rest-API. If I request list of MyEntity I get result like:

{
    "_links": {
      "self": {"href": "http://localhost:8080/api/MyEntity/1"},
      "second": {"href": "http://localhost:8080/api/MyEntity/1/second"}
    }
},
{
    "_links": {
      "self": {"href": "http://localhost:8080/api/MyEntity/2"},
      "second": {"href": "http://localhost:8080/api/MyEntity/2/second"}
    }
}

If I want check, is [0].second == [1].second, I need to do two extra request. It is not good.

Maybe possible to configure RestResource that it gave the following resource?

{
    "_links": {
      "self": {"href": "http://localhost:8080/api/MyEntity/1"},
      "second": {"href": "http://localhost:8080/api/SecondEntity/12"}
    }
},
{
    "_links": {
      "self": {"href": "http://localhost:8080/api/MyEntity/2"},
      "second": {"href": "http://localhost:8080/api/SecondEntity/45"}
    }
}

Solution

  • You can do this using projections feature of Spring Data REST

    Here is an explanation https://spring.io/blog/2014/05/21/what-s-new-in-spring-data-dijkstra#user-content-projections-in-spring-data-rest

    Here is a similar question How to return representations of associations in a Spring Data REST resource?