Scrivio Interview library
DebuggingFoundations6 min read · updated 12 November 2026

A developer is surprised that an UPDATE is sent to the database even though they never called save:

Java
@Transactional
public OrderDto view(Long id) {
Order o = repo.findById(id).orElseThrow();
o.setTotal(o.getTotal().setScale(2));
return map(o);
}

Explain.

The Order returned by findById() is a managed entity inside the transaction, so changing its total for display is a real change as far as Hibernate is concerned, and dirty checking writes it with an UPDATE when the transaction commits. We should never modify entities for presentation; we map them to a DTO and format there. Marking the method @Transactional(readOnly = true) also stops the write, because with Hibernate Spring sets the flush mode to manual, and BigDecimal is a type where even changing the scale can count as a change.

Why this question is asked

This bug is dangerous because it looks harmless: a view method, a small formatting step, and suddenly the database receives writes from what should be a read. In the worst case, the display formatting rounds a value and the rounded value is stored, changing financial data. Interviewers ask it to see whether we connect managed entities, dirty checking and transaction settings. In this answer, we will reproduce the surprise, explain why the UPDATE happens, look closely at BigDecimal and scale, and then fix it in two independent ways.

1A Quick Recap: Loaded Entities Are Managed

Inside a @Transactional method, every entity we load through a repository belongs to the persistence context, the per-transaction map Hibernate keeps of the entities it tracks. Hibernate takes a snapshot of each loaded entity's values. When the transaction commits, it flushes: it compares each managed entity with its snapshot and writes an UPDATE for each one that differs. This is dirty checking.

So for a managed entity, a setter call is a request to change the database. Hibernate cannot tell whether we called setTotal() to save a correction or only to make the number look nicer on a page; both are changes.

2Reproducing the Surprise

Here is the method with SQL logging turned on. Suppose the total column is numeric(19,4) and the stored value is 99.9950.

Java
@Transactional
public OrderDto view(Long id) {
Order o = repo.findById(id).orElseThrow(); // select ... from orders where id=? (total = 99.9950)
o.setTotal(o.getTotal().setScale(2, RoundingMode.HALF_UP)); // 100.00: the entity changed
return map(o);
}
// at commit: update orders set ..., total=100.00 where id=?
// the stored total is now 100.0000 instead of 99.9950
Step throughHow a display change becomes a write
ControllerOrderService proxyPersistence contextDatabase
view(42)
begin transaction
findById(42)
SELECT order 42
setTotal(rounded): entity is dirty
OrderDto
flush before commit
UPDATE orders set total = 100.00
commit

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

The DTO is returned, but the commit after it writes the display value.

Notice what just happened: a read endpoint rounded a stored amount and saved the rounded value. Every customer who opens the page changes the data. In the question's version, setScale(2) is called without a rounding mode. That call cannot change the numeric value: it either only adds or removes trailing zeros, or throws an ArithmeticException when rounding would be needed. So whether it triggers an UPDATE depends on how dirty checking compares BigDecimal values, which we look at next.

3Why Scale Matters for BigDecimal

A BigDecimal holds an unscaled integer and a scale, the number of digits after the decimal point. 10.5 and 10.50 have the same numeric value but different scales, and BigDecimal.equals() treats them as different, while compareTo() says they are equal.

Java
BigDecimal a = new BigDecimal("10.5000");
BigDecimal b = a.setScale(2); // 10.50
System.out.println(a.equals(b)); // false: equals() compares value and scale
System.out.println(a.compareTo(b) == 0); // true: same numeric value
new BigDecimal("10.125").setScale(2); // ArithmeticException: rounding necessary

Dirty checking compares old and new values with the equality rule of the attribute's type. If that rule is equals(), a scale-only change looks like a change and produces an UPDATE. Hibernate's own BigDecimal handling has used a numeric comparison in recent versions, in which case only a real change of value, like the rounding above, is written; check your version rather than relying on either behaviour. The lesson is the same either way: with BigDecimal, small-looking formatting calls can produce a value that dirty checking sees as new, and any real rounding certainly is.

4Fix 1: Format in the DTO, Not in the Entity

The root cause is that presentation logic changed a domain object. The entity should hold the stored value; the formatting belongs to the mapping step, which creates a new object that Hibernate does not track.

Java
record OrderDto(long id, String total) {}
private OrderDto map(Order o) {
String shown = o.getTotal().setScale(2, RoundingMode.HALF_UP).toPlainString(); // a new value, entity untouched
return new OrderDto(o.getId(), shown); // "100.00"
}
// at commit: nothing is dirty, no UPDATE

Now the entity is never modified, so dirty checking finds nothing. This fix is correct whatever the transaction settings are, which is why it comes first.

5Fix 2: Mark Read Methods readOnly

The second fix protects against the next mistake of the same kind. When we write @Transactional(readOnly = true) and the JPA provider is Hibernate, Spring sets the Hibernate session's flush mode to MANUAL, so no automatic flush runs at commit, and recent Spring versions also mark the session read-only, so Hibernate does not even keep snapshots for loaded entities. The JDBC connection is also flagged read-only, which some drivers and databases use for routing or optimisation.

Java
@Transactional(readOnly = true)
public OrderDto view(Long id) {
Order o = repo.findById(id).orElseThrow(); // select
return map(o);
} // no flush, no UPDATE, no snapshots kept

But there is a catch: readOnly is a safety net, not permission to modify entities. Code that later calls flush() explicitly, or the same entity used again in a writing transaction, can still carry the changed value. So we use both: format in the DTO, and mark read methods read-only.

6Follow-up questions

Would the UPDATE happen without @Transactional on the method?

With Spring Data's default, findById() runs in its own short read-only transaction inside the repository, and the entity is detached when it returns, so the setter would change only a detached object and nothing would be written. With open-in-view enabled the entity can stay managed for the request, and then any later writing transaction in the same request would flush the shared persistence context and write the change too. Here the method's own @Transactional provides the writing transaction directly.

How would we catch this kind of bug in tests?

Assert the SQL statements of read use cases. A test that counts statements with Hibernate statistics or datasource-proxy and expects zero updates for view() fails the moment a display change leaks into an entity.

Is it ever fine to call setters in a read path?

Only for transient, non-persistent fields marked @Transient, which Hibernate ignores. Even then a DTO is usually clearer, because it keeps the entity a faithful copy of the database row.

7Conclusion

In this answer, we saw that the order is managed inside the transaction, so the change made for display is detected by dirty checking and written at commit. We saw that BigDecimal carries a scale and that equals() treats 10.5 and 10.50 as different, so formatting calls can produce values that count as changes, and real rounding always does. The fixes are to format in a DTO instead of the entity and to mark read methods @Transactional(readOnly = true), which with Hibernate switches the flush mode to manual.

What to say in the interviewAbout 90 seconds aloud

Open with

The order comes from findById inside a transaction, so it is a managed entity, and Hibernate took a snapshot of it when it loaded it. Calling setTotal is, as far as Hibernate knows, a real change.

Then, if they want more

At commit it flushes, dirty checking compares the total with the snapshot, sees a difference and sends an UPDATE. Nobody needs to call save for that. The developer meant it as formatting, but Hibernate cannot tell display intent from a business change.

With BigDecimal this is easy to trigger, because a BigDecimal has a scale: 10.5 and 10.50 are not equal by equals, and if the formatting rounds, for example setScale with HALF_UP, the stored amount is actually overwritten with the rounded value, which is a data corruption bug coming from a read endpoint. I would fix it in two ways.

First, never modify entities for presentation: map the entity to a DTO and do the scaling and formatting there, so the entity is untouched and nothing is dirty. Second, mark read methods with Transactional readOnly true.

With Hibernate, Spring then sets the session flush mode to manual and marks the session read-only, so even if someone modifies an entity by mistake, nothing is flushed, and Hibernate also skips keeping snapshots. I would also add a test that asserts zero update statements for read use cases.

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 developer is surprised that an UPDATE is sent to the database even though they never...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/bb16fd3c8d/