Scrivio Interview library
DesignIntermediate8 min read · updated 12 November 2026

Design a ledger of account postings that must never be updated or deleted, mapped with JPA. How do you enforce immutability at every layer?

We enforce immutability at every layer, because each layer alone can be bypassed. The entity is marked @Immutable, has no setters and is built complete by one constructor; the database role the application uses has no UPDATE or DELETE privilege on the table (or a trigger rejects changes); mistakes are corrected with new compensating postings; the entity can use a READ_ONLY second-level cache; and tests prove that every attempt to change a posting fails.

Why this question is asked

A ledger is the record of money moving between accounts. Accountants and auditors rely on one property above all others: a posting, once written, stays exactly as it was. If a developer, a bulk script or a bug can quietly change last month's postings, balances stop being trustworthy and the audit trail is worthless. Interviewers ask this question because it tests whether we understand that an annotation in Java code is only one line of defence. In this answer, we will recap what immutability means for a JPA entity, build the entity, then lock down the database, look at how corrections work without edits, add caching that immutability makes safe, and finish with tests that prove the rules hold.

1A Quick Recap: What Can Change a Row?

Before designing defences, it helps to list the ways a row in a posting table can change. The first is the normal JPA path: code loads an entity, calls a setter, and at flush time Hibernate compares the entity with the snapshot it took when loading (this is called dirty checking) and writes an UPDATE. The second is a bulk JPQL or native statement such as UPDATE Posting p SET p.amount = 0, which goes straight to the database and never looks at entities. The third is anything outside the application: a migration script, a support engineer with a SQL console, or another service sharing the database.

So a design that only stops the first path is incomplete. We want the Java model to make changes impossible to write by accident, and the database to refuse changes that slip through anyway. Then we need a business answer for the legitimate need to fix a wrong posting, and tests to keep all of this true as the code evolves.

2Building the Entity So It Cannot Be Changed

In the Java layer we make the entity read like a value. It gets the Hibernate annotation @Immutable (org.hibernate.annotations.Immutable), which tells Hibernate never to dirty check it and never to issue an UPDATE for it. It has no setters at all. Every field is set once, in a public constructor that takes everything a posting needs, and the constructor validates the values so an incomplete posting cannot exist.

Java
@Entity
@Table(name = "posting")
@Immutable
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@Access(AccessType.FIELD) // Hibernate reads and writes fields, not getters
public class Posting {
@Id
private UUID id;
private String accountId;
private BigDecimal amount; // positive = credit, negative = debit
private String currency;
private Instant bookedAt;
private UUID correctsPostingId; // null unless this posting reverses another
protected Posting() { } // for Hibernate only
public Posting(UUID id, String accountId, BigDecimal amount, String currency,
Instant bookedAt, UUID correctsPostingId) {
this.id = Objects.requireNonNull(id);
this.accountId = Objects.requireNonNull(accountId);
this.amount = Objects.requireNonNull(amount);
this.currency = Objects.requireNonNull(currency);
this.bookedAt = Objects.requireNonNull(bookedAt);
this.correctsPostingId = correctsPostingId;
}
public BigDecimal getAmount() { return amount; } // getters only
}

Notice the protected no-argument constructor. JPA needs it to create instances when it loads rows, but keeping it protected means our own code cannot use it to build a half-empty posting. Field access matters too: with @Access(AccessType.FIELD) Hibernate sets fields directly by reflection, so it does not need setters to load data.

What about final fields? The JPA specification says persistent fields must not be final, so a portable design keeps them private and non-final with no setters. Hibernate can usually populate final fields through reflection, and some teams use that, but it is provider behaviour rather than a guarantee, so check your version and keep a test if you rely on it. The real protection comes from having no way to call a mutator, not from the final keyword.

There is a catch with @Immutable worth knowing. If someone does change a field on a managed immutable entity, Hibernate simply ignores the change at flush; it does not throw. And @Immutable does not stop em.remove(): an immutable entity can still be deleted. For bulk HQL updates against an immutable entity, Hibernate has a setting (hibernate.query.immutable_entity_update_query_handling_mode) that decides between a warning and an exception, and the default has changed across versions, so set it to exception explicitly. These gaps are exactly why the database must enforce the rule too.

3Making the Database Refuse Changes

The strongest guarantee lives in the database, because every path from the list above ends there. The cleanest approach is permissions. The application connects as a role that may insert and select postings but has no UPDATE or DELETE privilege on that table. Schema migrations run as a different owner role.

SQL
-- run by the migration (owner) role
REVOKE UPDATE, DELETE, TRUNCATE ON posting FROM ledger_app;
GRANT SELECT, INSERT ON posting TO ledger_app;
-- as ledger_app:
UPDATE posting SET amount = 0 WHERE id = '...';
-- ERROR: permission denied for table posting
Step throughWhere immutability is enforced
  1. Teststry to update and delete, expect failure
  2. Domain rulescorrections are new compensating postings
  3. JPA entity@Immutable, no setters, complete constructor
  4. Second-level cacheREAD_ONLY strategy, never invalidated
  5. Databaseno UPDATE or DELETE privilege, or a rejecting trigger

5 layers, from the top down. Step through them one at a time.

Each layer catches a different way of changing a posting; the database is the one that cannot be bypassed by application code.

When we cannot control roles, for example because one shared account is used everywhere, a trigger gives the same effect. A BEFORE UPDATE OR DELETE trigger that raises an exception rejects every change, whoever sends it. Triggers are a little weaker than privileges because the table owner can disable them, but they still catch scripts and bugs. Either way, the database now rejects changes from bulk queries, consoles and other services, which no Java annotation could do.

4Correcting Mistakes Without Editing

A ledger still needs a way to fix errors. Suppose a payment of 120.00 was posted to the wrong account. We never edit that posting. Instead we write a compensating posting of -120.00 on the same account that points back to the original through correctsPostingId, and then a new correct posting of 120.00 on the right account. The balance of each account is the sum of its postings, so both balances become right, and the history shows exactly what happened and when.

This is how accounting has always worked on paper, and it fits the software well. The reason is that a balance computed from postings is reproducible at any point in time: we can ask what the balance was on 31 March and get the same answer next year. An edited posting would silently change that historical answer. So the service exposes operations like reverse(postingId, reason) and never anything like update(posting).

5Caching That Immutability Makes Safe

Immutability has a nice side effect on performance. Hibernate's second-level cache, a cache shared across sessions, normally has to deal with entries going stale when another transaction updates a row. For an entity that never changes, the READ_ONLY concurrency strategy is the simplest and fastest choice: entries are written once and never need invalidation. Hibernate will refuse attempts to update a READ_ONLY cached entity, which adds one more check. If the provider supports query caching, queries over old, closed periods can also be cached safely, because their results cannot change.

6Proving It With Tests

Rules like these erode quietly when someone adds a setter or a convenient bulk update a year later. So we write tests that try to break them, against a real database in a container (for example with Testcontainers), using the application role.

Java
@Test
void appRoleCannotUpdatePostings() {
assertThatThrownBy(() -> jdbc.update("UPDATE posting SET amount = 0"))
.isInstanceOf(DataAccessException.class); // permission denied
}
@Test
void entityChangesAreNeverWritten() {
Posting p = repo.save(newPosting("120.00"));
ReflectionTestUtils.setField(p, "amount", BigDecimal.ZERO);
repo.flush();
assertThat(jdbc.queryForObject("SELECT amount FROM posting WHERE id = ?",
BigDecimal.class, p.getId())).isEqualByComparingTo("120.00"); // unchanged
}
@Test
void postingHasNoSetters() {
assertThat(Arrays.stream(Posting.class.getMethods())
.filter(m -> m.getName().startsWith("set"))).isEmpty(); // true
}

Notice that each test targets a different layer: the first proves the database refuses the change, the second proves Hibernate ignores an in-memory change, and the third is a small architecture rule that fails the build if someone adds a setter. A test for the delete privilege works the same way as the first one.

7Follow-up questions

Why not rely on @Immutable alone?

Because it only controls what Hibernate does for loaded entities. It does not stop em.remove(), it may only warn on bulk HQL updates depending on configuration, and it has no effect on native SQL, migration scripts or other services. The database privileges are the layer that holds no matter which code path sends the statement.

How do we compute balances efficiently if postings are never updated?

We usually keep a separate balance or snapshot table that is updated in the same transaction as the insert, or recomputed per period, and treat it as derived data that can be rebuilt from postings at any time. The postings stay the source of truth, and the snapshot is a performance aid that may be mutable because it can always be recalculated.

Can we use a Java record for the posting?

Not as a JPA entity. Records are final and have no no-argument constructor, and entities need both for proxies and loading. Records work well as the DTO or command that carries posting data into the service, and as projections when reading postings.

8Conclusion

In this answer, we saw that immutability has to be enforced at every layer because each one can be bypassed on its own. The entity is @Immutable, has only getters and a complete validating constructor, and uses field access; the database role cannot update or delete postings, or a trigger rejects it; mistakes are fixed with compensating postings that keep history intact; the READ_ONLY cache strategy becomes safe and cheap; and tests at each layer keep the rules true over time.

What to say in the interviewAbout 80 seconds aloud

Open with

I would enforce it at several layers, because each one can be bypassed on its own. In the entity I'd use Hibernate's @Immutable, field access, no setters, a protected no-arg constructor for Hibernate and a public constructor that builds a complete, validated posting.

Then, if they want more

I'd point out that the spec doesn't allow final persistent fields, so I rely on having no mutators rather than on final. I'd also mention that @Immutable just ignores dirty changes, doesn't block remove, and may only warn on bulk HQL updates, so I'd configure that to throw.

The real guarantee is in the database: the application role gets SELECT and INSERT on the posting table but no UPDATE or DELETE, and migrations run as a separate owner. If roles aren't under our control, a trigger that rejects updates and deletes does the same job.

For the business side, corrections are always new compensating postings that reference the original, so balances at any past date stay reproducible. Because postings never change, the READ_ONLY second-level cache strategy is safe.

Finally I'd add tests against a real database: an update as the app role must fail, a reflective change to a managed posting must not reach the row, and an architecture test fails if anyone adds a setter.

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 "Design a ledger of account postings that must never be updated or deleted, mapped with...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/1d33b85cc0/