Scrivio Interview library
ConceptIntermediate6 min read · updated 12 November 2026

Why should a controller not bind request bodies directly to JPA entities? Give a concrete risk.

Binding a request body straight onto a JPA entity lets clients set any field the entity has, which is mass assignment: a concrete risk is a customer sending "price": 0.01 or "role": "ADMIN", or an id that makes save() overwrite someone else's row. It also mixes input validation with persistence rules, and ties the public API contract to the database model, so every entity change becomes an API change. Separate request and response DTOs, mapped explicitly, avoid all three problems.

Why this question is asked

Using the entity as the request body is tempting because it saves a class and a mapping. It is also one of the most common sources of real security bugs in Spring APIs. Interviewers ask for a concrete risk because a vague answer about layering is easy; showing exactly how a field gets changed proves we understand the mechanism. In this answer, we will recap what @RequestBody does, reproduce a concrete attack, then look at the validation and contract problems, and finish with the DTO-based fix.

1A Quick Recap of @RequestBody Binding

When a controller parameter has @RequestBody, Spring passes the body to Jackson, which creates an instance of the parameter type and sets every property that appears in the JSON. Jackson does not know which fields the client is allowed to set. If a property in the JSON matches a setter, a field or a constructor parameter, it is set.

An entity, on the other hand, holds everything the system knows about a row: its id, its owner, its status, its audit fields, prices and flags that only the system should change. Binding the body onto it hands all of those to the client.

2A Concrete Risk: Changing the Price

Here is an order line endpoint that binds onto the entity.

Java
@Entity
public class OrderLine {
@Id @GeneratedValue Long id;
@ManyToOne Order order;
String sku;
int quantity;
BigDecimal unitPrice; // set by the pricing service, not the client
boolean discountApproved; // set by a manager
}
@PostMapping("/orders/{orderId}/lines")
OrderLine add(@PathVariable long orderId, @RequestBody OrderLine line) {
line.setOrder(orders.getReferenceById(orderId));
return lines.save(line);
}
// Intended request: {"sku": "TV-55", "quantity": 1}
// Attacker sends: {"sku": "TV-55", "quantity": 1, "unitPrice": 0.01, "discountApproved": true}
// Saved row: unitPrice = 0.01, discountApproved = true
Step throughHow a client sets a field it should not
ClientJacksonOrderLine entityDatabase
JSON with unitPrice 0.01
new OrderLine(); set every field in the JSON
save(): INSERT with unitPrice 0.01
201, line saved at 0.01

4 messages in order. Play them, or step through them one at a time.

Jackson sets whatever the JSON contains; the entity cannot tell input fields from internal ones.

Notice that the developer probably meant to set unitPrice from the pricing service later in the method, and forgot, or set it only when it was null. Either way, the client controls it. A worse variant is the id: if the JSON contains "id": 981, save() calls merge, and Hibernate updates the existing line 981, which may belong to another customer's order. The same pattern lets users change role, ownerId or tenantId on a profile or account endpoint.

3Input Rules and Persistence Rules Are Different

The second problem is validation. The rules for what a client may send are not the same as the rules for a valid row. A new line request needs a sku and a positive quantity; it must not contain an id or a price. The entity needs a non-null price and an order before it can be saved. If both sets of annotations live on the entity, they collide: @NotNull on unitPrice makes the create request fail unless the client sends a price, which is exactly what we do not want, and removing it weakens the persistence rule.

The rules also differ per operation. Creating a customer requires an email; a partial update does not. With one entity class we end up with validation groups on every field, or with no validation at all, which is what usually happens.

4The Entity Becomes the API Contract

The third problem is coupling. With the entity as request and response type, its fields are the API. Renaming a column renames a JSON property and breaks clients. Adding an internal field, such as costPrice, adds it to every response and makes it settable in every request, without anyone deciding so. Bidirectional relations can make responses recurse, and lazy fields can fail during serialisation.

The database model should be free to change for database reasons, and the API should change only through a deliberate, versioned decision. Using one class for both makes that impossible.

5The Fix: Request and Response DTOs With Explicit Mapping

We give each operation its own request type with only the fields the client may send, and a response type with only the fields we want to expose. The service maps between them and the entity, and fills internal fields from trusted sources.

Java
public record AddLineRequest(@NotBlank String sku, @Positive int quantity) {}
public record LineDto(long id, String sku, int quantity, BigDecimal unitPrice) {}
@PostMapping("/orders/{orderId}/lines")
ResponseEntity<LineDto> add(@PathVariable long orderId, @Valid @RequestBody AddLineRequest req) {
LineDto created = orderService.addLine(orderId, req);
return ResponseEntity.created(locationOf(created)).body(created);
}
@Transactional
public LineDto addLine(long orderId, AddLineRequest req) {
Order order = orders.findOwnedByCurrentUser(orderId); // ownership checked
OrderLine line = order.addLine(req.sku(), req.quantity(),
pricing.priceFor(req.sku())); // price from the server
return LineDto.from(line);
}
// Attacker's extra fields: unitPrice, discountApproved, id -> ignored, no such properties

Notice what the request record cannot express: there is no id, no price and no approval flag, so no JSON can set them. By default Spring Boot configures Jackson to ignore unknown properties, so the extra fields are silently dropped; some teams set spring.jackson.deserialization.fail-on-unknown-properties=true for strict APIs so clients learn about mistakes. Validation on the record expresses exactly the input rules, and the entity keeps its own persistence rules. The response record defines what clients see, and new entity fields stay private until someone adds them to it.

6Follow-up questions

Is @JsonIgnore on the sensitive entity fields enough?

It helps for the fields we remember, but it is a deny-list on a class that keeps growing. The next developer adds a field and forgets the annotation. It also cannot express per-operation rules, such as a field that is settable on create but not on update. DTOs are an allow-list by construction.

Doesn't this add a lot of mapping code?

Some, but it is simple code, and records keep it short. MapStruct can generate the mapping when DTOs have many fields. The mapping is also where we put decisions, such as where the price comes from, so it is code we would need anyway.

7Conclusion

In this answer, we saw that binding a request body onto a JPA entity lets clients set any of its fields, and showed a concrete risk: a client setting unitPrice to 0.01 or sending an id that overwrites another row. We also saw that input validation and persistence validation differ, and that the entity becomes the API contract. Separate request and response DTOs, validated and mapped explicitly in a service that fills internal fields from trusted sources, remove all three problems.

What to say in the interviewAbout 80 seconds aloud

Open with

Because Jackson sets every property that appears in the JSON, and an entity has properties the client should never control. A concrete example: an endpoint adds an order line by binding @RequestBody OrderLine.

Then, if they want more

The intended body is just sku and quantity, but an attacker adds "unitPrice": 0.01 and a discount flag, and both get saved. Or they include an id, and save() merges into an existing row, possibly someone else's. On user endpoints the same thing lets people change their role or tenant. That's mass assignment. There are two more reasons.

Input validation isn't the same as persistence validation: a create request must not contain a price, while the row must have one, and putting both on the entity makes the annotations fight. And the entity becomes the API contract, so renaming a column or adding an internal field like a cost price changes the API without anyone deciding to.

So I use a request record per operation, with only the fields the client may send and validation for them, and a response record with what we choose to expose. The service maps explicitly, takes the price from the pricing service and the owner from the authenticated user, and new entity fields stay private by default.

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 "Why should a controller not bind request bodies directly to JPA entities? Give a...": https://scrivio-interview-library.netlify.app/spring-boot/rest-controllers/111e272ae9/