Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

Write a Spring Data JPA native upsert for PostgreSQL that increments a counter row or inserts it if missing, and explain the transactional and persistence-context implications.

We declare a @Modifying native @Query that runs insert into page_view(page_id, views) values (:id, 1) on conflict (page_id) do update set views = page_view.views + 1, and call it from a @Transactional service method. The statement is atomic in PostgreSQL, so concurrent increments are never lost. But it bypasses the persistence context: a PageView entity already loaded is now stale, so we clear automatically or reload it, and we evict any second-level cache entries for that table.

Why this question is asked

Counters are a classic place where a naive read-modify-write loses updates: two requests read 41, both write 42, and one view disappears. Interviewers like this question because the database-side fix is short, but using it correctly from JPA requires understanding transactions, the persistence context and caching. In this answer, we will recap what an upsert is, write the repository method, see why it does not lose updates, and then go through the transaction it needs and the stale entity and cache problems it leaves behind.

1A Quick Recap of Upserts

An upsert is an insert that turns into an update when the row already exists. PostgreSQL spells it insert ... on conflict (column) do update. The conflict target, page_id here, must be covered by a unique index or primary key, because that is how PostgreSQL detects that the row is already there.

Inside the do update clause, page_view.views refers to the value already stored in the row, and excluded.views would refer to the value we tried to insert. So views = page_view.views + 1 means add one to whatever is stored now.

SQL
create table page_view (
page_id bigint primary key, -- the conflict target needs a unique constraint
views bigint not null
);

2Writing the Repository Method

In Spring Data JPA, any query that changes data must be marked with @Modifying, otherwise Spring Data runs it as a select and fails because no result set comes back. nativeQuery = true tells it to send the SQL as written.

Java
public interface PageViewRepository extends JpaRepository<PageView, Long> {
@Modifying
@Query(value = """
insert into page_view(page_id, views) values (:id, 1)
on conflict (page_id) do update set views = page_view.views + 1
""", nativeQuery = true)
int increment(@Param("id") long id); // 1: one row inserted or updated
}
@Service
class PageViewService {
private final PageViewRepository repo;
PageViewService(PageViewRepository repo) { this.repo = repo; }
@Transactional
public void recordView(long pageId) {
repo.increment(pageId); // first call inserts views = 1, later calls add 1
}
}

The int return value is the number of rows the statement affected. For an upsert it is 1 whether PostgreSQL inserted or updated, so it tells us the statement worked but not which branch it took. If we need that, PostgreSQL can return values with a returning clause, which we would read as a query result instead.

3Why No Update Is Lost

The broken version loads the entity, adds one in Java, and saves it. Between the load and the save, another request can do the same, and the second save overwrites the first.

The upsert avoids this because the read and the write happen inside one statement on the database. When two transactions upsert the same page_id, the second waits for the row lock the first one holds, then reads the committed value and adds one to it. When the row does not exist yet, PostgreSQL's unique index makes one insert win and turns the other into the update path, without a duplicate key error.

Java
// Broken under concurrency: read-modify-write in Java
PageView pv = repo.findById(pageId).orElseGet(() -> new PageView(pageId, 0));
pv.setViews(pv.getViews() + 1); // both threads read 41 and set 42
repo.save(pv); // final value 42 instead of 43
Step throughTwo concurrent upserts on the same page
Request APostgreSQLRequest B
upsert page 7: lock row, views 41 -> 42
upsert page 7: waits for A's row lock
commit
lock granted, reads 42, writes 43
commit

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

The row lock serializes the two increments, so the final value is 43.

4It Must Run Inside a Transaction

JPA only executes update and insert queries inside an active transaction. If increment() is called with no transaction, Hibernate throws a TransactionRequiredException with a message about executing an update or delete query. Query methods we declare ourselves do not get a write transaction from Spring Data by default, so we put @Transactional on the calling service method, as above, or on the repository method itself.

Notice also that the transaction defines when the increment becomes visible. If the service method does more work after increment() and then throws, the increment is rolled back with everything else, which is usually what we want.

5The Persistence Context Does Not See the Change

The persistence context is the set of entities Hibernate has loaded in the current transaction, each kept with its state. A native statement runs straight in the database, so Hibernate does not update any PageView it already holds. Reading it again in the same transaction returns the cached object, not the new row.

Java
@Transactional
public long viewAndRead(long pageId) {
PageView before = repo.findById(pageId).orElseThrow(); // views = 41, now managed
repo.increment(pageId); // database has 42
PageView after = repo.findById(pageId).orElseThrow(); // same object as before
return after.getViews(); // 41: stale
}

There are two fixes. @Modifying(clearAutomatically = true) clears the persistence context after the statement, so the next findById goes to the database and returns 42. Its partner flushAutomatically = true flushes pending changes before the statement, so our own unsaved edits are not lost when the context is cleared. Alternatively we call entityManager.refresh(before) on the one entity we care about, which is cheaper when the context holds many other entities.

6Evicting the Second-Level Cache

If PageView is cached in Hibernate's second-level cache, the cache shared across transactions, the native statement does not update it either. By default, when Hibernate executes a native update it cannot tell which entities changed, so it invalidates all cache regions, which is correct but expensive. If we narrow that with Hibernate's synchronized entity settings, or if the cache sits outside Hibernate, we must evict the entry ourselves.

Java
@Transactional
public void recordView(long pageId) {
repo.increment(pageId);
entityManagerFactory.getCache().evict(PageView.class, pageId); // next read loads 42 from the database
}

For a hot counter, the simplest answer is often not to cache the entity at all, because a value that changes on every request gains nothing from a cache.

7Follow-up questions

Why not use a pessimistic lock with findById and save?

It works, with @Lock(PESSIMISTIC_WRITE) the second request waits for the first, but it needs two round trips, holds the lock while Java code runs, and still has a race when the row does not exist yet, because there is nothing to lock. The upsert does the whole thing in one statement and handles the missing row through the unique index.

What does flushAutomatically add?

It flushes the persistence context before the modifying query runs. That matters when the same transaction has changed entities that the query depends on, or when clearAutomatically would otherwise throw away those unsaved changes. Using both flags together is a safe default for bulk and native modifying queries.

How do we know whether the row was inserted or updated?

Add returning (xmax = 0) as inserted to the statement and run it as a query rather than an update, so it returns a value. xmax = 0 is a PostgreSQL-specific trick that is true for a freshly inserted row; it relies on internal behaviour, so a simpler option is to return the new views value and treat 1 as an insert.

8Conclusion

In this answer, we wrote a native PostgreSQL upsert as a @Modifying @Query that inserts a counter row or increments it. Because the read and write happen in one statement, row locks and the unique index make concurrent increments safe. The method must run inside a transaction, it leaves loaded PageView entities stale, so we use clearAutomatically with flushAutomatically or refresh the entity, and any second-level cache entry for the row must be evicted.

What to say in the interviewAbout 70 seconds aloud

Open with

I would write a repository method with @Modifying and a native @Query: insert into page_view(page_id, views) values (:id, 1) on conflict (page_id) do update set views = page_view.views + 1, returning int. page_id needs a primary key or unique index, because that is how PostgreSQL detects the conflict.

Then, if they want more

This is atomic in the database: two requests for the same page are serialized by the row lock, and a missing row is resolved by the unique index, so no increment is lost, unlike loading the entity, adding one in Java and saving it.

The method must run in a transaction, so I put @Transactional on the service method; without one Hibernate throws TransactionRequiredException. The catch is the persistence context. The native statement does not touch entities Hibernate already loaded, so a PageView read earlier in the transaction would still show the old count.

I set clearAutomatically = true, usually with flushAutomatically = true so pending changes are written first, or I refresh the entity. And if PageView is in the second-level cache, I evict it, though for a counter I would rather not cache it at all.

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 "Write a Spring Data JPA native upsert for PostgreSQL that increments a counter row or...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/dd100b0ae9/