Search code examples
javaspringspring-bootspring-dataspring-data-rest

Is is possible to define a custom Spring Data GET Endpoint, which includes additional data?


I need to find a way to modify data created by Spring Data endpoints, before the data gets serialized. The problem is as follows:

Base Situation

There is a Entity Orders, which basically is structured like this:


public Class Order {
  public String name;
  public Long uuid;    // id of the user
}

For this Entity also a corresponding OrderRespository exists.

Now when I fetch the data using the Spring Data Endpoint GET /api/orders I can retrieve the list of orders. I can also query e.g. for any property of the actuality much bigger entity, for example the name property (using GET /api/orders?name=order42).

Problem

But now the actual problem comes into play: I have to make an additional step though and add the actual Usernames to the returned Data. So I need to return an OrderDTO like this:


public Class OrderDTO {
  public String name;
  public String username;    // actual name of the user, the order belongs to
}

How can I create an endpoint, that has all the query/pagination abilities of the Spring Data Endpoint, while still being able to write custom code to fetch and assign the username (which comes from an external system)? The solution might also be to modify the data returned from Spring Data, before it is being serialized.


Solution

  • I solved it using Projections:

    @Value("#{@userService.getUpdatedByUserName(target)}")
    String getUpdatedByUserName();
    

    userService is the name of the UserService Spring Bean in this case.

    See the Spring Data JPA Docs, Example 91