Video in progress
What happens to unflushed changes when you call `em.clear()` or `em.detach()`?
They silently disappear. clear() and detach() remove entities from the context, and the pending INSERTs/UPDATEs are cancelled too. That's why in batch jobs the order is always flush() and then clear(); and in Spring Data, @Modifying(clearAutomatically = true) should be paired with flushAutomatically = true.
📖 Answer
On one project an import job finished "successfully", but the database was missing a few rows after every 500th record. This was the cause:
for (int i = 0; i < rows.size(); i++) {
Product p = repo.findBySku(rows.get(i).sku()).orElseThrow();
p.setPrice(rows.get(i).price()); // dirty, but not flushed yet
if (i % 500 == 0) {
em.clear(); // the changes were lost here
}
}
The findBySku query had flushed some changes because of FlushMode.AUTO, but others were still pending before the clear() and vanished. No error, a clean log: the worst kind of bug.
The right order:
if (i % 500 == 0) {
em.flush(); // first the SQL goes to the database
em.clear(); // then the memory is freed
}
detach(entity) is the same: that entity's unsaved changes are discarded, and the ones linked through CascadeType.DETACH leave the context too.
Another trap after a clear: if you're still holding a reference to objects loaded earlier, they are now detached. Changing them does nothing, and their lazy associations throw LazyInitializationException. So in a loop, keep only ids, not objects.
In Spring Data the same rule applies:
@Modifying(flushAutomatically = true, clearAutomatically = true)
If you set only clearAutomatically, changes made before the bulk query can be lost.
Sign up to mark studied questions and save your progress.