Quick revision
The short answer
These mistakes come from a missing mental model of entity states and dirty checking, so the fix is to teach that model once and then make the mistakes visible automatically. We would write a short internal guide, add ArchUnit or static analysis rules for the common misuses, assert SQL statement counts in tests, run training with real examples from our own code, and give a platform team ownership of persistence patterns and of reviewing hot paths.
What to remember
In this answer, we traced the three misuses back to one missing model of entity states and dirty checking, and saw the concrete cost of each: no-op saves, an extra SELECT for every merge of a new entity, and lost changes after a stray clear(). The plan teaches the model with a short guide and real examples, then keeps it in place with ArchUnit and static rules, statement count assertions in tests, and a platform team that owns the patterns and reviews hot paths.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
These mistakes come from a missing mental model of entity states and dirty checking, so the fix is to teach that model once and then make the mistakes visible automatically. We would write a short internal guide, add ArchUnit or static analysis rules for the common misuses, assert SQL statement counts in tests, run training with real examples from our own code, and give a platform team ownership of persistence patterns and of reviewing hot paths.
Why this question is asked
Misused JPA operations rarely break features; they make services quietly slower and their behaviour harder to predict. A save() after every setter adds nothing, but a merge() for a new entity adds a SELECT to every insert, and a stray clear() can detach entities that later code still changes, so those changes are lost. Interviewers ask this at senior level to see whether we can fix a skill gap across many teams rather than in one pull request. In this answer, we will see why each mistake happens, then build the plan in the order we would roll it out: guide, automated checks, statement counts, training and ownership.
1Why Each Mistake Happens
The three habits share one root cause: developers treat JPA like a remote call that needs an explicit save, instead of a unit of work that tracks managed entities. Once we understand that loaded entities are managed and dirty checking writes their changes at flush, the save() after every setter is visibly pointless.
The merge for new entities with assigned ids is more subtle. Spring Data's save() asks whether the entity is new. With an assigned id and no @Version field, it sees a non-null id, decides the entity is not new and calls merge(). merge() must then run a SELECT to find out whether the row exists before it inserts. Every insert costs two statements. The fix is to call persist(), implement Persistable so isNew() returns the truth, or add a @Version field so Spring Data can tell new from existing.
Random clear() calls usually come from someone fighting a memory problem in a batch job. clear() detaches every managed entity, so changes made afterwards to objects loaded earlier are silently not saved, and later lazy loads fail.
2Step One: A Short Guide Based on Entity States
The guide should fit in a few pages, because a long one is not read. It explains the four entity states, what dirty checking does at flush, when save() is actually needed (for new entities and for detached ones we want to reattach), how Spring Data decides between persist and merge, and when clear() is appropriate (inside a batch loop, after a flush, with nothing held across it). Each rule comes with a before and after snippet and the SQL log, because seeing two statements turn into one convinces people faster than prose.
We would put the guide next to the code, in the repository of the shared persistence library, so it changes in the same pull requests as the patterns it describes.
3Step Two: Automated Rules That Catch the Common Mistakes
Rules in a tool scale better than reviewers. ArchUnit, a library that checks architecture rules in ordinary unit tests, can forbid calls to EntityManager.clear() outside a batch package, forbid repositories from being used in controllers, or require that entities with assigned ids implement Persistable or have a @Version field. Static analysis rules (for example custom Error Prone or Sonar rules, check what your build already runs) can flag a save() call on a variable that came from findById() in the same method.
4Step Three: Statement Count Assertions in Tests
Most of these mistakes show up as extra SQL. If tests assert how many statements a use case runs, the extra SELECT from a merge or the extra UPDATE from a needless save fails a build instead of reaching production. We can count statements with Hibernate's statistics, enabled in tests with hibernate.generate_statistics=true, or with a JDBC proxy library such as datasource-proxy.
Notice that the test documents the expected cost of the use case. When someone changes the mapping, the number in the test tells reviewers what changed in the database.
5Step Four: Training With Our Own Code
Generic JPA courses use toy entities. Training works better when we take real snippets from our own repositories, anonymised if needed, run them with SQL logging on and ask the group to predict the statements before we show them. A ninety-minute session per team, followed by a short exercise of fixing one real finding in their own service, makes the guide concrete. We would record the session and link it from the guide for new joiners.
6Step Five: Ownership of Persistence Patterns
Without an owner, guides go stale and rules get switched off. A small platform team, or a guild with named members, owns the shared persistence configuration, the ArchUnit rules and the guide. It also reviews the hot paths of each service, the handful of endpoints and jobs that carry most of the load, because that is where a pattern mistake costs the most.
We would measure progress with numbers we can actually collect: statements per request on the top endpoints, the count of rule violations per repository, and slow-query reports. If statements per order placement drop from five to two across services, the programme is working.
- Collect real findingsfrom code reviews and SQL logs
- Write the short guideentity states, dirty checking, save, merge, clear
- Add ArchUnit and static rulesfail the build on known mistakes
- Assert statement countsfor each important use case
- Train with our own codepredict the SQL, then run it
- Platform team owns itrules, guide, review of hot paths
- Statements per request falling?Yeskeep tightening the rulesNorevisit training and rules
7 steps in order. Play them, or step through them one at a time.
7Follow-up questions
Should we simply forbid calling save() on existing entities?
Not as a blanket rule, because save() is needed for new entities and for detached ones. The rule we want is narrower: no save() on an entity that was loaded in the same transaction. That is what the static rule and the statement count tests catch.
When is EntityManager.clear() legitimate?
In batch processing, after a flush() every few hundred entities, so the persistence context does not grow without limit and dirty checking stays cheap. The code must not use entities loaded before the clear() afterwards, because they are detached.
How do we get teams to adopt the rules without resentment?
Start the ArchUnit rules in a warning mode or with a recorded list of existing violations, so new code is held to the rule while old code is fixed gradually. Teams accept rules more easily when each one links to the guide entry that explains why it exists.
8Conclusion
In this answer, we traced the three misuses back to one missing model of entity states and dirty checking, and saw the concrete cost of each: no-op saves, an extra SELECT for every merge of a new entity, and lost changes after a stray clear(). The plan teaches the model with a short guide and real examples, then keeps it in place with ArchUnit and static rules, statement count assertions in tests, and a platform team that owns the patterns and reviews hot paths.
Open with
I would start by recognising that all three mistakes come from the same gap: people do not have a clear picture of entity states and dirty checking. If you know that loaded entities are managed and changes are written at flush, a save after every setter is obviously redundant.
Then, if they want more
Merge for new entities with assigned ids is the expensive one, because Spring Data sees a non-null id, calls merge, and merge runs a select before every insert; the fix is persist, Persistable, or a version field. Random clear calls detach everything and silently drop later changes.
So first I would write a short internal guide with the states, when save is actually needed and when clear is legitimate, each rule shown with the SQL before and after. Then I would make mistakes visible automatically: ArchUnit rules, for example clear only in batch packages, and static analysis for save on an entity loaded in the same method.
I would add statement count assertions to the tests of important use cases, using Hibernate statistics or datasource-proxy, so an extra select fails the build. I would run training using real snippets from our own code where people predict the SQL first.
Finally, a platform team would own the persistence patterns, maintain the rules, and review the hot paths of each service, and we would track statements per request on top endpoints to see whether it is working.
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.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 "Code reviews across teams show frequent misuse of JPA operations: save() called after...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/c2249f10b7/