Scrivio Interview library
ScenarioAdvanced7 min read · updated 12 November 2026

A public API returns JPA entities directly in 30 endpoints, and adding a field to an entity has leaked internal data twice. How would you fix this across the codebase?

I would treat it as an incident first and a refactoring second. The leaked data is reviewed and reported to security, then each of the 30 endpoints gets its own response DTO, starting with the ones that expose the most sensitive entities. Contract tests fail when a response shape changes, an ArchUnit rule stops controllers from returning entity types, and a published OpenAPI spec becomes the contract, so adding a field to an entity can never again change the public API by accident.

Why this question is asked

Returning JPA entities from controllers feels harmless until an entity gains a field. Then Jackson serialises it on every endpoint that returns that entity, and nobody reviewed that change as an API change. When it has already leaked internal data twice, the question is no longer whether to fix it, but how to fix 30 endpoints safely and make sure it cannot happen again. Interviewers ask this to see whether we handle the security side as well as the code. In this answer, we will see exactly why entity changes leak, handle the past leaks, introduce response DTOs in a sensible order, lock the shapes with contract tests and an architecture rule, and publish the spec as the contract.

1Why Adding an Entity Field Leaks Data

When a controller returns an object, Jackson writes every property it can see: every public getter, and by default every field with a getter. A JPA entity holds everything the database row holds. So the API's response shape is not something anyone designed; it is whatever the entity looks like today.

Here is how the two leaks probably happened. Someone added an internal field for a good reason, and the API changed silently.

Java
@Entity
public class Customer {
@Id Long id;
String name;
String email;
BigDecimal creditLimit; // added in March for the risk team
String internalRiskNote; // added in June for support staff
// getters for all fields
}
@GetMapping("/customers/{id}")
Customer get(@PathVariable long id) { return customers.findById(id).orElseThrow(); }
// Response before March: {"id":7,"name":"Ana","email":"ana@example.com"}
// Response after June: {"id":7,"name":"Ana","email":"ana@example.com",
// "creditLimit":5000.00,"internalRiskNote":"late payer, watch"}

Notice that the developer who added internalRiskNote changed the entity, the database migration and the support screen, and never touched the controller. The code review showed no API change, because there was none in the code. That is the core problem: the contract is implicit, so nothing can review or test it.

2Handle the Leaks as a Security Issue

Before refactoring, we deal with what already happened. The first step is to stop the bleeding: a quick patch with @JsonIgnore on the leaked fields, deployed today, while the proper fix follows. Then we inform the security team and, with them, work out the exposure: which fields were exposed, on which endpoints, since which release, and to which clients. Gateway logs with client ids tell us who called those endpoints in that period.

Security and legal then decide whether this is a reportable data breach, for example personal data under GDPR, and whether partners must be told. That is not an engineering decision, but engineering must supply the facts quickly and accurately. A short post-incident review records the root cause, entities as API types, so the fix that follows is understood as a response to it rather than as a style preference.

3Introduce Response DTOs, Most Sensitive First

The real fix is a response DTO per endpoint, or per resource representation, that lists exactly the fields we choose to publish. A record makes it short, and a static factory or a mapper converts the entity inside the service, while the transaction is still open.

Java
public record CustomerDto(long id, String name, String email) {
static CustomerDto from(Customer c) {
return new CustomerDto(c.getId(), c.getName(), c.getEmail());
}
}
@GetMapping("/customers/{id}")
CustomerDto get(@PathVariable long id) { return customerService.get(id); }
// Response: {"id":7,"name":"Ana","email":"ana@example.com"}
// Adding a field to Customer now changes nothing here until someone adds it to CustomerDto
Order of work for the 30 endpoints
PriorityEndpointsWhy
1Customer, Account, Payment (8)Personal and financial data; already leaked
2Most called by partners (10)Largest audience for any future leak
3Remaining endpoints (12)Lower risk, fixed in the normal flow of work

The first DTO must produce exactly the same JSON the endpoint returns today, minus the fields that leaked, so existing clients do not break. That includes property names, date formats and null handling. For 30 endpoints, I would order the work by risk: endpoints over entities with personal or financial data first, such as Customer, Account and Payment, then the most called endpoints, then the rest. With a few people, this is weeks of work, not months, and each endpoint ships on its own.

4Lock the Shapes With Contract Tests

A DTO alone could still drift: someone adds a field to it without thinking. So every endpoint gets a test that pins its response shape and fails when it changes. With @WebMvcTest and a JSON comparison in strict mode, an unexpected extra field fails the build.

Java
@WebMvcTest(CustomerController.class)
class CustomerContractTest {
@Autowired MockMvc mvc;
@MockitoBean CustomerService service;
@Test
void customerResponseShapeIsStable() throws Exception {
when(service.get(7)).thenReturn(new CustomerDto(7, "Ana", "ana@example.com"));
mvc.perform(get("/customers/7"))
.andExpect(content().json("""
{"id":7,"name":"Ana","email":"ana@example.com"}""", JsonCompareMode.STRICT));
}
}
// Someone adds creditLimit to CustomerDto -> test fails: Unexpected field "creditLimit"

Notice that the failure is the point: adding a field now forces a deliberate decision, visible in the pull request, that the field belongs in the public API. Consumer-driven contract tools such as Spring Cloud Contract or Pact go further and check the shapes partners actually depend on, which is worth adding for the most important partners. Check your Spring version for the exact JSON comparison API; older versions use a boolean strict flag.

5Block Entities in Controller Signatures

Contract tests protect the endpoints we have. An architecture rule protects the ones we will write next year. ArchUnit can fail the build if any controller method returns, or takes, a type annotated with @Entity, including inside generic types such as List or ResponseEntity if we write the condition carefully.

Java
@ArchTest
static final ArchRule controllersDoNotReturnEntities =
methods().that().areDeclaredInClassesThat().areAnnotatedWith(RestController.class)
.should(new ArchCondition<JavaMethod>("not return JPA entities") {
@Override
public void check(JavaMethod m, ConditionEvents events) {
boolean leaks = m.getReturnType().getAllInvolvedRawTypes().stream()
.anyMatch(t -> t.isAnnotatedWith(Entity.class));
if (leaks) events.add(SimpleConditionEvent.violated(m, m.getFullName() + " returns an entity"));
}
});
// Build fails: CustomerController.get(long) returns an entity
Step throughGuards that stop the next leak
  1. Developer adds a field to an entityNo API change intended
  2. Does any controller return the entity?ArchUnit rule in the build
    YesBuild failsNoResponse DTO unchanged
  3. Developer adds the field to a DTODeliberate API change
  4. Contract test still passes?Strict JSON comparison
    YesMergeNoUpdate test and spec in review
  5. Published OpenAPI spec changesBreaking-change check, partners notified

5 steps in order. Play them, or step through them one at a time.

While the migration is in progress, the rule can be frozen with FreezingArchRule, so the existing violations are recorded and only new ones fail. The list of frozen violations then doubles as our progress tracker: when it is empty, all 30 endpoints are done.

6Publish the OpenAPI Spec as the Contract

Finally, the public API needs an explicit contract that partners and reviewers can see. Once the DTOs exist, generating the spec with springdoc-openapi produces an accurate document, which we review, publish in the developer portal and keep in the repository. From then on, changes to the spec go through review, and a breaking-change check such as oasdiff in CI compares each build with the published version.

For a public API, I would go one step further over time and make the spec the source of truth, API-first, so the representation is designed before code. Either way, the response shape is now something people decide, review and test, instead of a side effect of the database model.

7Follow-up questions

Isn't @JsonIgnore on sensitive fields enough?

It is the right emergency patch, but not a fix. It is a deny-list on a class that keeps growing, and the next developer who adds a field will forget it, which is exactly how the second leak happened after the first. A DTO is an allow-list: nothing is published unless someone writes it down.

Could Jackson views or a mix-in replace DTOs?

They can control which fields are written, and they are useful in some cases, but they still start from the entity, so new fields appear unless the view excludes them, and they keep the API tied to entity structure, lazy loading and relations. For a public API, explicit DTOs are simpler to reason about and test.

8Conclusion

In this answer, we saw that returning JPA entities makes the response shape follow the database model, so a new internal field becomes public without any API change in the code. We handled the past leaks with an immediate patch and a review with security, introduced response DTOs endpoint by endpoint starting with the most sensitive data, pinned every response shape with strict contract tests, blocked entity return types with a frozen ArchUnit rule, and published an OpenAPI spec reviewed and checked for breaking changes as the contract.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd start with the security side, because data has already leaked twice. Same day, I'd patch the leaked fields with @JsonIgnore as a stopgap, then work with the security team on the exposure: which fields, which endpoints, since when, and which clients called them, using gateway logs.

Then, if they want more

They and legal decide whether it's reportable and whether partners must be told. Then the real fix. The root cause is that the response shape is whatever the entity looks like, so any new column becomes public without an API change in the code.

Each endpoint gets a response DTO, a record that lists exactly the published fields, mapped from the entity in the service. The first version must produce the same JSON as today minus the leaked fields, so clients don't break. I'd order the 30 endpoints by risk: personal and financial data first, then the most used, then the rest.

To stop it coming back, every endpoint gets a contract test with strict JSON comparison, so any change in shape fails and has to be a deliberate decision in review. An ArchUnit rule blocks controllers from returning entity types, frozen at first so it doubles as a progress tracker.

And we publish an OpenAPI spec as the contract, with a breaking-change check in CI.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A public API returns JPA entities directly in 30 endpoints, and adding a field to an...": https://scrivio-interview-library.netlify.app/spring-boot/rest-controllers/66eb25d7a9/