Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

Teams have scattered business logic in @PrePersist and @PreUpdate callbacks, leading to surprising behaviour and hard-to-test code. What guideline would you set?

The guideline is that callbacks are for technical concerns only: timestamps, version helpers and normalising formats on the entity's own fields. Business rules belong in domain methods and application services, where they are explicit and testable, and callbacks must never do I/O, remote calls or EntityManager queries. Auditing goes through Envers or a dedicated audit mechanism with clear ownership, and we enforce the rules with reviews and ArchUnit tests on listener classes.

Why this question is asked

Business logic in @PrePersist and @PreUpdate feels convenient: it runs automatically, no one can forget to call it. That is exactly the problem. Logic that runs implicitly at flush time runs at moments developers do not expect, in an order they did not choose, and only when Hibernate decides an entity is dirty. Interviewers ask this to see whether we can turn a pattern of surprises into a clear rule that teams will actually follow. In this answer, we will see why callback logic surprises people, state the guideline, move a real rule out of a callback, and set up enforcement.

1Why Callback Logic Surprises People

Callbacks run during the flush, not when the code that changed the entity runs. A @PreUpdate that recalculates an order's discount runs at commit, after the service method has already returned a response built with the old discount. It runs only if Hibernate found the entity dirty, so a rule that should apply on every save silently does not run when nothing else changed. It does not run at all for JPQL bulk updates or native SQL. And its order relative to other callbacks and other entities is hard to reason about.

Callbacks are also hard to test. To exercise the discount rule we need a persistence context and a flush, which means an integration test with a database, while the same rule in a domain method is a plain unit test that runs in milliseconds.

Java
@Entity
class Order {
@PreUpdate
void applyLoyaltyDiscount() {
if (customer.getTier() == Tier.GOLD) discount = total.multiply(new BigDecimal("0.10")); // business rule
}
}
// service sets total = 200.00 and returns OrderDto(discount = 0) <- response built before flush
// at commit: @PreUpdate sets discount = 20.00 <- the stored value differs from the response
// customer.getTier() may also trigger a lazy load during flush

2The Guideline in Five Rules

First, callbacks only handle technical concerns on the entity's own fields: setting createdAt and updatedAt, helping with versioning fields, and normalising formats such as trimming whitespace or lowercasing an email. If removing the callback would change a business outcome, it does not belong there.

Second, business rules live in domain methods on the entity, such as order.applyDiscount(policy), and in application services that call them. There they run when the code says so, they are visible in the method that changes the state, and they can be unit tested.

Third, no I/O in callbacks: no remote calls, no messages, no file access, no EntityManager operations and no queries. The JPA specification already forbids EntityManager and query use in portable callbacks, and external calls inside a flush can happen before a rollback.

Fourth, auditing goes through Hibernate Envers or a dedicated audit mechanism owned by a named team, not through ad hoc callbacks in each entity. Fifth, the rules are enforced by reviews and by architecture tests, so they do not depend on memory.

Where each kind of logic belongs
LogicCallback?Where instead
Set createdAt, updatedAtyes-
Trim and lowercase an emailyes-
Loyalty discount, pricingnodomain method called by the service
Validation of business rulesnodomain method or application service
Audit historynoEnvers or the audit module
Send event or emailnoafter-commit listener or outbox

3Moving a Rule Out of a Callback

Here is the discount rule as a domain method. The service calls it explicitly at the moment the business operation happens, so the response and the stored value agree.

Java
@Entity
class Order {
public void applyLoyaltyDiscount(Tier tier) {
discount = (tier == Tier.GOLD) ? total.multiply(new BigDecimal("0.10")) : BigDecimal.ZERO;
}
}
@Transactional
public OrderDto updateTotal(long id, BigDecimal total) {
Order o = orders.findById(id).orElseThrow();
o.setTotal(total);
o.applyLoyaltyDiscount(customers.tierOf(o.getCustomerId())); // explicit, in the use case
return map(o); // discount = 20.00 in the response and the database
}
@Test void goldGetsTenPercent() { // a plain unit test, no database
Order o = new Order(new BigDecimal("200.00"));
o.applyLoyaltyDiscount(Tier.GOLD);
assertThat(o.getDiscount()).isEqualByComparingTo("20.00"); // passes
}

Notice what changed: the rule runs where we can see it, with its input passed in, and the test needs no persistence context. Migrating existing callbacks works the same way, one rule at a time, with an integration test proving the stored values stay the same.

4Enforcing the Guideline

We write the guideline as a short page with the five rules and the before and after example, and add it to the review checklist. Then we let the build enforce what can be enforced. ArchUnit can check that listener classes and methods annotated with @PrePersist or @PreUpdate do not depend on repositories, EntityManager, HTTP clients or messaging classes.

Java
@ArchTest
static final ArchRule listenersStayTechnical =
noClasses().that().haveSimpleNameEndingWith("Listener").and().resideInAPackage("..persistence..")
.should().dependOnClassesThat().resideInAnyPackage(
"jakarta.persistence.criteria..", "org.springframework.data.repository..",
"org.springframework.kafka..", "org.springframework.web.client..")
.because("callbacks handle technical fields only; no queries, repositories or remote calls");
// fails: OrderPricingListener depends on org.springframework.data.repository.CrudRepository

Rules on callback methods inside entities need a custom ArchUnit condition, for example that methods annotated with @PreUpdate only access fields of their own class, which a platform team can write once and share. Existing violations go into a frozen baseline, so the build blocks new ones while teams remove the old ones.

5Follow-up questions

Is normalising data in a callback not also a business rule?

Formatting that never changes meaning, such as trimming or lowercasing an email that is compared case-insensitively anyway, is technical. Anything that decides an outcome, like a price, a status or whether an operation is allowed, is business and belongs in explicit code.

What about Bean Validation on entities, which also runs at flush?

Hibernate Validator checks constraints such as @NotNull at pre-persist and pre-update as a safety net, which is fine. Validation that users need to see should still run earlier, at the API boundary or in the service, so errors are reported clearly rather than as an exception at commit.

Who should own the audit mechanism?

One team, usually the platform or data team, owns Envers configuration or the audit module, its schema and retention. Service teams mark what must be audited. That avoids each team building its own history tables with different semantics.

6Conclusion

In this answer, we saw why business logic in callbacks surprises people: it runs at flush, only for dirty entities, not for bulk SQL, and it is hard to test. The guideline limits callbacks to technical concerns on the entity's own fields, moves business rules into domain methods and services, forbids I/O, remote calls and EntityManager queries in callbacks, sends auditing to Envers or an owned audit mechanism, and enforces all of it with reviews and ArchUnit rules.

What to say in the interviewAbout 90 seconds aloud

Open with

I would set a simple rule: lifecycle callbacks are for technical concerns only. That means setting timestamps, helping with version fields and normalising formats on the entity's own fields, like trimming an email.

Then, if they want more

Business rules do not belong there, and I would explain why with a real example from our code. A PreUpdate that recalculates a discount runs at flush, after the service has already built its response, so the API returns one value and the database stores another.

It only runs if Hibernate thinks the entity is dirty, it never runs for bulk updates, and testing it needs a database. Moved into a domain method that the service calls explicitly, the same rule is visible in the use case and testable with a plain unit test.

The guideline also says no I/O in callbacks: no remote calls, no messages, no EntityManager queries, which the JPA spec already discourages and which is dangerous before commit. Auditing goes through Envers or a dedicated audit module with a clear owner instead of ad hoc callbacks.

To make it stick, I would put the rules and the before and after example on one page, add them to the review checklist, and add ArchUnit rules that stop listener classes from depending on repositories, EntityManager, HTTP clients or Kafka, with existing violations frozen in a baseline so teams fix them gradually while new ones fail the build.

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 "Teams have scattered business logic in @PrePersist and @PreUpdate callbacks, leading to...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/aafccbfa2c/