Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

What SQL does this code run, assuming the Customer exists and is not yet loaded? @Transactional

Java
void rename(Long id, String n) {
Customer c = em.find(Customer.class, id);
c.setName(n);
em.persist(c);
em.flush();
em.refresh(c);
}

The method runs three statements before the commit: a SELECT from find(), an UPDATE from flush() because dirty checking sees the new name, and a second SELECT from refresh(), which overwrites the in-memory state with what is now in the database. persist() on an entity that is already managed does nothing, and the flush at commit finds nothing left to write. Calling persist() or save() after a setter on a managed entity is unnecessary.

Background to this question

Questions like this test whether we can predict what Hibernate sends to the database, which is the skill we need when a service is slow or a log is full of unexpected statements. Each line here maps to a different part of the entity lifecycle, so reading it correctly shows that we know entity states, dirty checking and the difference between flush and commit. In this answer, we will recap the entity states, walk through the method one line at a time with the SQL each line causes, and then see what the clean version of the method looks like.

1A Quick Recap of Entity States

An entity object is in one of four states. A new object we just created with new is transient: Hibernate does not know it. A managed entity is one the persistence context tracks, either because we loaded it or because we persisted it. A detached entity was managed once, but its persistence context has closed. A removed entity is scheduled for deletion.

For managed entities, Hibernate keeps a snapshot of the values it loaded. At flush time it compares each managed entity with its snapshot and writes an UPDATE for anything that changed. This is called dirty checking, and it is why we never need to tell Hibernate that a managed entity changed.

2Walking Through the Method Line by Line

Here is the method again, with the SQL that each line causes as trailing comments. We assume the Customer with this id exists and is not in the persistence context when the method starts, and that the transaction was opened by the @Transactional proxy.

Java
@Transactional
void rename(Long id, String n) {
Customer c = em.find(Customer.class, id); // select c.id, c.email, c.name, ... from customer c where c.id=?
c.setName(n); // no SQL: only the Java field changes
em.persist(c); // no SQL: c is already managed, persist is ignored
em.flush(); // update customer set email=?, name=?, ... where id=?
em.refresh(c); // select ... from customer where id=? (again)
} // commit: the flush finds nothing dirty, so only COMMIT
Step throughWhat the database sees
rename()Persistence contextDatabase
find(Customer, id)
SELECT customer by id
row; snapshot kept
setName(n), persist(c): nothing sent
flush()
UPDATE customer (name changed)
refresh(c)
SELECT customer by id again
COMMIT (nothing left to flush)

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

Three statements and a commit. persist() on a managed entity adds nothing.

So the database sees SELECT, UPDATE, SELECT, COMMIT. The setter only changes a field in memory. persist() is defined for new entities; on a managed one, the specification says it is ignored, apart from cascading PERSIST to related entities that are new. The UPDATE lists all columns by default, not only name, because Hibernate prepares one UPDATE statement per entity at startup; @DynamicUpdate changes that.

3Why flush() Sends an UPDATE but Does Not Commit

flush() means: send every pending change to the database now. Hibernate compares c with its snapshot, sees that name differs, and executes the UPDATE inside the open transaction. The change is now in the database but not committed. Other transactions cannot see it yet, and if the method threw an exception after flush(), the rollback would undo it.

Without the explicit flush(), the UPDATE would still happen, just later, at the automatic flush that runs before commit. So the explicit flush only moves the statement earlier. That is useful when we need the database to see the change before something else runs, for example a native query, a trigger or a constraint check we want to fail here rather than at commit.

4What refresh() Does to the Object

refresh() throws away the in-memory state of c and reloads it from the database. Because the UPDATE was already flushed, the reloaded name is the new name, so in this method refresh() mostly costs a round trip. It becomes meaningful when the database changes the row itself, for example a trigger that sets updated_at, a column with a database default, or a computed column. After refresh(), the entity holds those database-generated values too.

But there is a catch: if we called refresh() before flush(), the reload would overwrite our unsaved name with the old value from the database, and the change would be lost silently. Order matters.

Java
c.setName("New");
em.refresh(c); // select ... : the unsaved change is overwritten
System.out.println(c.getName()); // Old

5The Clean Version

Most of this method is not needed. For a managed entity, changing the field is enough, and dirty checking writes it at commit. The same applies in Spring Data JPA: calling repository.save(c) on an entity we just loaded inside the transaction does nothing useful, because save() on an existing entity calls merge(), which for a managed entity simply returns it.

Java
@Transactional
void rename(Long id, String n) {
Customer c = em.find(Customer.class, id); // select
c.setName(n);
} // flush at commit: update; then COMMIT

Now the database sees one SELECT, one UPDATE and the commit. We keep flush() only when something in the same transaction must see the change in the database first, and refresh() only when the database computes values we need afterwards.

6Follow-up questions

What would happen if c were detached instead of managed?

persist() on a detached entity is an error; Hibernate throws an exception (wrapped by Spring as an InvalidDataAccessApiUsageException or similar, check your version) because the object looks like a new entity with an existing id. To apply changes from a detached object we would use merge(), which loads the current row and copies our values onto the managed copy.

Would the UPDATE run if setName() set the same value the entity already had?

No. Dirty checking compares values, not setter calls. If the new name equals the snapshot value, the entity is not dirty and flush sends nothing.

Does flush() commit the transaction?

No. flush() sends SQL inside the current transaction. The commit happens when the @Transactional method returns normally, and until then a rollback can still undo everything that was flushed.

7Conclusion

In this answer, we traced the method line by line. find() runs a SELECT and makes the customer managed, the setter only changes memory, persist() on a managed entity is ignored, flush() writes an UPDATE because dirty checking finds the new name, and refresh() runs a second SELECT that overwrites the object with the database state. The commit then has nothing left to flush. For managed entities, the setter alone is enough.

What to say in the interviewAbout 90 seconds aloud

Open with

I would say it runs three statements. The find runs a select by primary key, because the customer is not yet in the persistence context, and from then on the entity is managed with a snapshot of its loaded values.

Then, if they want more

The setter only changes the field in memory. The persist call is a no-op for a managed entity; persist is for new objects, so apart from cascading to new related entities it does nothing here. The flush runs dirty checking, sees that name differs from the snapshot and sends an update, by default with all columns.

That update is inside the transaction and not yet committed. Then refresh runs a second select and overwrites the in-memory state with what the database has, which here is the same new name, unless a trigger or default changed something. At commit, the automatic flush finds nothing dirty, so only the commit goes out.

The lesson I take from this code is that persist, or save in Spring Data, after setters on a managed entity is unnecessary, because dirty checking handles it. I would keep the explicit flush only if something later in the transaction must see the change in the database, and refresh only if the database generates values I need.

And I would never call refresh before flushing my own change, because it silently throws that change away.

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 "What SQL does this code run, assuming the Customer exists and is not yet loaded?...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/1ce976a4c9/