Video in progress
After Hibernate throws an exception, can you keep using the same `EntityManager`/`Session`?
No. According to the Hibernate documentation, after an exception in a Session you should roll back the transaction and close the Session, because the persistence context may be inconsistent with the database. In particular, after a ConstraintViolationException during flush, flushing again tries to send the same SQL again.
📖 Answer
The classic mistake is swallowing the error in a loop and carrying on:
@Transactional
public void importAll(List<Row> rows) {
for (Row r : rows) {
try {
em.persist(toEntity(r));
em.flush();
} catch (PersistenceException e) {
log.warn("skip {}", r.id()); // we carry on... wrong
}
}
}
What happens: after the first duplicate, JPA marks the transaction rollback-only. The entity that caused the error is still in the persistence context, and the next flush() tries to INSERT it again. On PostgreSQL, after an error the whole transaction is "aborted", and every following query gives current transaction is aborted. At the end, the commit throws UnexpectedRollbackException and nothing is saved.
The right ways:
- do each record in its own transaction (
REQUIRES_NEWorTransactionTemplate). Slower, but the errors are isolated; - prevent the error beforehand: first check for existing keys with a single query, or use a native
insert ... on conflict do nothing; - on PostgreSQL you can work with savepoints, but JPA doesn't support that natively.
NoResultException and NonUniqueResultException are the exceptions: they don't break the transaction. After any other PersistenceException, don't trust the context: roll back, start a new transaction, a new context.
Sign up to mark studied questions and save your progress.