Video in progress
How do you do "update if it exists, insert if it doesn't" (upsert) correctly with Hibernate?
findById + save creates a race condition with parallel requests: both see "doesn't exist" and both INSERT. The reliable way is the database's own upsert (insert ... on conflict do update on PostgreSQL, merge on others) through a native query, or a unique constraint plus catching the error and retrying.
📖 Answer
Code you see a lot, but broken:
@Transactional
public void track(String sku, int qty) {
Stock s = repo.findBySku(sku).orElseGet(() -> new Stock(sku));
s.add(qty);
repo.save(s);
}
If two requests arrive at the same time, both get an empty result from findBySku and both INSERT. With a unique constraint, one fails with an error; without one, you get duplicate rows.
On PostgreSQL I write a native upsert:
@Modifying
@Query(value = """
insert into stock(sku, qty) values (:sku, :qty)
on conflict (sku) do update set qty = stock.qty + excluded.qty""",
nativeQuery = true)
void upsert(@Param("sku") String sku, @Param("qty") int qty);
One atomic SQL statement, and the database resolves the lock and the race. The downside: the Stock copy in the persistence context isn't updated and lifecycle callbacks don't run, the same rules as for bulk queries.
Hibernate itself has a way too: since 6.3, StatelessSession.upsert(entity) builds database-appropriate merge/on conflict SQL. Handy for import jobs.
If you can't use native SQL: add a unique constraint, catch DataIntegrityViolationException, and rerun the whole operation once in a new transaction. It works, but the code is more complicated, and you must remember to discard the context after a failed transaction.
Sign up to mark studied questions and save your progress.