eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – Diagrid – NPI EA (cat= Testing)
announcement - icon

In distributed systems, managing multi-step processes (e.g., validating a driver, calculating fares, notifying users) can be difficult. We need to manage state, scattered retry logic, and maintain context when services fail.

Dapr Workflows solves this via Durable Execution which includes automatic state persistence, replaying workflows after failures and built-in resilience through retries, timeouts and error handling.

In this tutorial, we'll see how to orchestrate a multi-step flow for a ride-hailing application by integrating Dapr Workflows and Spring Boot:

>> Dapr Workflows With PubSub

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)