1. Overview

As we know, the Spring Data Rest module can make our life easier when we want to start quickly with RESTful web services. However, this module comes with a default behavior, which can sometimes be confusing.

In this tutorial, we’ll learn why Spring Data Rest doesn’t serialize entity ids by default. Also, we’ll discuss various solutions to change this behavior.

2. Default Behavior

Before we get into details, let’s understand what we mean by serializing the entity id with a quick example.

So, here is a sample entity, Person:

@Entity
public class Person {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    // getters and setters

}

Additionally, we have a repository, PersonRepository:

public interface PersonRepository extends JpaRepository<Person, Long> {

}

In case we’re using Spring Boot, simply adding the spring-boot-starter-data-rest dependency enables the Spring Data Rest module:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>

With those two classes and Spring Boot’s auto-configuration, our REST controllers are automatically ready to use.

As a next step, let’s request the resource, http://localhost:8080/persons, and check the default JSON response generated by the framework:

{
    "_embedded" : {
        "persons" : [ {
            "name" : "John Doe",
            "_links" : {
                "self" : {
                    "href" : "http://localhost:8080/persons/1"
                },
                "person" : {
                    "href" : "http://localhost:8080/persons/1{?projection}",
                    "templated" : true
                }
            }
        }, ...]
    ...
}

We’ve omitted some parts for brevity. As we notice, only the name field is serialized for the entity Person. Somehow, the id field is stripped out.

Accordingly, this is a design decision in Spring Data Rest. Exposing our internal ids, in most cases, isn’t ideal because they mean nothing to external systems.

In an ideal situation, the identity is the URL of that resource in RESTful architectures.

We should also see that this is only the case when we use Spring Data Rest’s endpoints. Our custom @Controller or @RestController endpoints aren’t affected unless we use Spring HATEOAS‘s RepresentationModel and its children — like CollectionModel, and EntityModel — to build our responses.

Luckily, exposing entity ids is configurable. So, we still have the flexibility to enable it.

In the next sections, we’ll see different ways of exposing entity ids in Spring Data Rest.

3. Using RepositoryRestConfigurer

The most common solution for exposing entity ids is configuring RepositoryRestConfigurer:

@Configuration
public class RestConfiguration implements RepositoryRestConfigurer {

    @Override
    public void configureRepositoryRestConfiguration(
      RepositoryRestConfiguration config, CorsRegistry cors) {
        config.exposeIdsFor(Person.class);
    }
}

Before Spring Data Rest version 3.1 – or Spring Boot version 2.1 – we’d use RepositoryRestConfigurerAdapter:

@Configuration
public class RestConfiguration extends RepositoryRestConfigurerAdapter {
    @Override
    public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(Person.class);
    }
}

Although it’s similar, we should pay attention to versions. As a side note, since Spring Data Rest version 3.1  RepositoryRestConfigurerAdapter is deprecated and it has been removed in the latest 4.0.x branch.

After our configuration for the entity Person, the response gives us the id field as well:

{
    "_embedded" : {
        "persons" : [ {
            "id" : 1,
            "name" : "John Doe",
            "_links" : {
                "self" : {
                    "href" : "http://localhost:8080/persons/1"
                },
                "person" : {
                    "href" : "http://localhost:8080/persons/1{?projection}",
                    "templated" : true
                }
            }
        }, ...]
    ...
}

Apparently, when we want to enable id exposure for all of them, this solution isn’t practical if we have many entities.

So, let’s improve our RestConfiguration via a generic approach:

@Configuration
public class RestConfiguration implements RepositoryRestConfigurer {

    @Autowired
    private EntityManager entityManager;

    @Override
    public void configureRepositoryRestConfiguration(
      RepositoryRestConfiguration config, CorsRegistry cors) {
        Class[] classes = entityManager.getMetamodel()
          .getEntities().stream().map(Type::getJavaType).toArray(Class[]::new);
        config.exposeIdsFor(classes);
    }
}

As we use JPA to manage persistence, we can access the metadata of the entities in a generic way. JPA’s EntityManager already stores the metadata that we need. So, we can practically collect the entity class types via entityManager.getMetamodel() method.

As a result, this is a more comprehensive solution since the id exposure for every entity is automatically enabled.

4. Using @Projection

Another solution is to use the @Projection annotation. By defining a PersonView interface, we can expose the id field too:

@Projection(name = "person-view", types = Person.class)
public interface PersonView {

    Long getId();

    String getName();

}

However, we should now use a different request to test, http://localhost:8080/persons?projection=person-view:

{
    "_embedded" : {
        "persons" : [ {
            "id" : 1,
            "name" : "John Doe",
            "_links" : {
                "self" : {
                    "href" : "http://localhost:8080/persons/1"
                },
                "person" : {
                    "href" : "http://localhost:8080/persons/1{?projection}",
                    "templated" : true
                }
            }
        }, ...]
    ...
}

To enable projections for all the endpoints generated by a repository, we can use the @RepositoryRestResource annotation on the PersonRepository:

@RepositoryRestResource(excerptProjection = PersonView.class)
public interface PersonRepository extends JpaRepository<Person, Long> {

}

After this change, we can use our usual request, http://localhost:8080/persons, to list the person entities.

However, we should note that excerptProjection doesn’t apply single item resources automatically. We still have to use http://localhost:8080/persons/1?projection=person-view to get the response for a single Person together with its entity id.

Besides, we should keep in mind that the fields defined in our projection aren’t always in order:

{
    ...            
    "persons" : [ {
        "name" : "John Doe",
        "id" : 1,
        ...
    }, ...]
    ...
}

In order to preserve the field order, we can put the @JsonPropertyOrder annotation on our PersonView class:

@JsonPropertyOrder({"id", "name"})
@Projection(name = "person-view", types = Person.class)
public interface PersonView { 
    //...
}

5. Using DTOs Over Rest Repositories

Overwriting rest controller handlers is another solution. Spring Data Rest lets us plug in custom handlers. Hence, we can still use the underlying repository to fetch the data, but overwrite the response before it reaches the client. In this case, we’ll write more code, but we’ll have the power of full customization.

5.1. Implementation

First of all, we define a DTO object to represent our Person entity:

public class PersonDto {

    private Long id;

    private String name;

    public PersonDto(Person person) {
        this.id = person.getId();
        this.name = person.getName();
    }
    
    // getters and setters
}

As we can see, we add an id field here, which corresponds to Person‘s entity id.

As a next step, we’ll use some built-in helper classes to reuse Spring Data Rest’s response building mechanism while keeping the response structure same as much as possible.

So, let’s define our PersonController to override the built-in endpoints:

@RepositoryRestController
public class PersonController {

    @Autowired
    private PersonRepository repository;

    @GetMapping("/persons")
    ResponseEntity<?> persons(PagedResourcesAssembler resourcesAssembler) {
        Page<Person> persons = this.repository.findAll(Pageable.ofSize(20));
        Page<PersonDto> personDtos = persons.map(PersonDto::new);
        PagedModel<EntityModel<PersonDto>> pagedModel = resourcesAssembler.toModel(personDtos);
        return ResponseEntity.ok(pagedModel);
    }

}

We should notice some points here to be sure that Spring recognizes our controller class as a plug-in, rather than an independent controller:

  1. @RepositoryRestController must be used instead of @RestController or @Controller
  2. PersonController class must be placed under a package that Spring’s component scan can pick up Alternatively, we can define it explicitly using @Bean.
  3. @GetMapping path must be the same as the PersonRepository provides. If we customize the path with @RepositoryRestResource(path = “…”), then the controller’s get mapping must also reflect this.

Finally, let’s try our endpoint, http://localhost:8080/persons:

{
    "_embedded" : {
        "personDtoes" : [ {
            "id" : 1,
            "name" : "John Doe"
        }, ...]
    }, ...
}

We can see the id fields in the response.

5.2. Drawbacks

If we go with DTO over Spring Data Rest’s repositories, we should consider a few aspects.

Some developers aren’t comfortable with serializing entity models directly into the response. Surely, it has some drawbacks. Exposing all entity fields could cause data leaks, unexpected lazy fetches, and performance issues.

However, writing our @RepositoryRestController for all endpoints is a compromise. It takes away some of the benefits of the framework. Besides, we need to maintain a lot more code in this case.

6. Conclusion

In this article, we discussed multiple approaches for exposing entity ids when using Spring Data Rest.

As usual, we can find all the code samples used in this article over on Github.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.