Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

A @DataJpaTest saves an entity that violates a unique constraint, but the test that expects an exception fails because nothing is thrown. Why?

save() only puts the entity into Hibernate's persistence context; the INSERT is sent later, at flush time, and @DataJpaTest wraps every test in a transaction that is rolled back at the end, so the flush never happens and the database never checks the unique constraint. Calling saveAndFlush() or entityManager.flush() inside the test sends the SQL and the exception appears. The id strategy changes the timing: with IDENTITY, Hibernate must insert immediately to get the id, so the error shows up at save() itself.

Why this question is asked

This one confuses people because everything looks right: the constraint exists, the second entity clearly duplicates the first, and assertThrows is there. Yet the test fails with 'Expected DataIntegrityViolationException to be thrown, but nothing was thrown'. Interviewers like it because the answer depends on two things every JPA developer should understand, when Hibernate actually talks to the database and what a test transaction does. In this answer, we will recap the persistence context and flushing, reproduce the failing test, follow why no SQL is ever sent, fix it, and see why the id generation strategy changes the result.

1A Quick Recap of the Persistence Context and Flushing

When we call repository.save(entity) for a new entity, Spring Data calls entityManager.persist(entity). Persist does not mean 'run an INSERT now'. It means 'start managing this object'. Hibernate puts the entity into the persistence context, a kind of in-memory workspace for the current transaction, and remembers that it must be inserted.

The actual SQL is sent when Hibernate flushes. Flushing is the moment Hibernate turns the pending changes in the persistence context into INSERT, UPDATE and DELETE statements. By default it flushes when the transaction commits, before a JPQL or native query that could be affected by the pending changes, and whenever we call flush() ourselves. Delaying writes this way lets Hibernate batch statements and skip work that turns out to be unnecessary.

The unique constraint lives in the database. Only the database can check it, and only when it receives the INSERT. Until the flush, there is nothing to violate.

2Reproducing the Problem

Here is the failing test. The customer table has a unique constraint on email, and the entity uses a sequence for its id, which is the common default with Hibernate 6 on PostgreSQL.

Java
@Entity
class Customer {
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE) Long id;
@Column(unique = true, nullable = false) String email;
// constructors omitted
}
@DataJpaTest
class CustomerRepositoryTest {
@Autowired CustomerRepository customers;
@Test
void rejectsDuplicateEmail() {
customers.save(new Customer("ann@example.com"));
assertThrows(DataIntegrityViolationException.class,
() -> customers.save(new Customer("ann@example.com")));
// AssertionFailedError: Expected DataIntegrityViolationException to be thrown, but nothing was thrown
}
}

If we turn on SQL logging with spring.jpa.show-sql=true, we see the clue straight away: the log shows two calls to fetch the next sequence value and no INSERT at all. Hibernate needed ids, so it asked the sequence, but it never sent the rows.

3Why the Database Never Sees the Duplicate

@DataJpaTest is meta-annotated with @Transactional. Spring's test framework starts a transaction before each test method and rolls it back after the method, so every test leaves the database clean. That is convenient, but it changes the default flush point. The commit, which is where Hibernate would normally flush, never happens; a rollback discards the pending changes without sending them.

So the sequence of events is this. The first save() schedules an insert. The second save() schedules another insert for a different object with the same email. Hibernate has no reason to compare them; it does not know about the unique constraint at runtime. The lambda returns normally, so assertThrows fails. Then the test ends and Spring rolls back, throwing away both pending inserts. The database was never asked anything except for two sequence values.

Step throughTwo saves that never reach the table
TestRepositoryPersistence contextDatabase
save(ann)
persist: schedule insert
nextval for the id
save(ann again)
persist: schedule second insert
nextval for the id
returns normally, nothing thrown
end of test: rollback, no INSERT sent

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

The constraint can only fail when an INSERT reaches the database, and none ever does.

4The Fix: Flush Inside the Test

We make Hibernate send the SQL while the test is still running. The simplest way is saveAndFlush(), which saves and then flushes the persistence context.

Java
@Test
void rejectsDuplicateEmail() {
customers.saveAndFlush(new Customer("ann@example.com")); // INSERT sent, row 1 exists
assertThrows(DataIntegrityViolationException.class,
() -> customers.saveAndFlush(new Customer("ann@example.com"))); // INSERT sent, constraint fails
// passes
}
// Alternatively, with TestEntityManager or EntityManager:
// customers.save(new Customer("ann@example.com"));
// assertThrows(PersistenceException.class, () -> {
// customers.save(new Customer("ann@example.com"));
// entityManager.flush(); // Hibernate ConstraintViolationException, a PersistenceException
// });

Notice the different exception types. A call through the Spring Data repository goes through Spring's exception translation, so the Hibernate error becomes Spring's DataIntegrityViolationException. A direct call to EntityManager.flush() is not translated, so it throws Hibernate's own ConstraintViolationException, which is a jakarta.persistence.PersistenceException. The test should expect the type that matches where the flush happens.

Also notice that the first save should be flushed too, or at least the flush must happen inside the assertThrows block. If we flush only after assertThrows, the exception is thrown outside the lambda and the test fails for a different reason. After a constraint violation, the transaction is marked for rollback, so the test should not do further database work after the expected failure.

5Why the Id Strategy Changes the Timing

Now change the id mapping to GenerationType.IDENTITY, which uses an auto-increment column. With IDENTITY, the database creates the id during the INSERT, so Hibernate cannot know the id without inserting the row. Because persist must give the entity an id, Hibernate sends the INSERT immediately, at save() time, instead of waiting for the flush.

Java
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id;
customers.save(new Customer("ann@example.com")); // INSERT sent now, id = 1
customers.save(new Customer("ann@example.com")); // INSERT sent now, DataIntegrityViolationException

So the same test passes with IDENTITY and fails with SEQUENCE. That is why a test like this can break after someone changes the id strategy for better batching, and why we should never rely on the id strategy to make a constraint test work. Flushing explicitly makes the test say what it means, whatever the mapping. The same goes for entities with assigned ids: Spring Data calls merge() for an entity whose id is already set, which may run a SELECT first, but the INSERT is still delayed until a flush.

6Follow-up questions

Why does @DataJpaTest roll back by default?

So that each test starts from the same database state without manual cleanup. The test framework starts a transaction before the test and rolls it back afterwards. The side effect is that anything Hibernate would only do at commit, such as flushing, deferred constraint checks or @TransactionalEventListener callbacks, does not happen unless we trigger it. We can opt out with @Commit or @Rollback(false), but then we must clean up ourselves.

Would the test behave the same on H2 and PostgreSQL?

The flushing problem is the same on both, because it is about Hibernate, not the database. But the constraint must actually exist in the schema the test uses. With a generated schema, it exists only if the entity declares it, for example with @Column(unique = true) or a @Table uniqueConstraints entry. A constraint that only the Flyway migration creates is missing from a generated H2 schema, which is another reason to test against the real engine with migrations.

Is calling flush in production code a good idea?

Usually not. In production the commit flushes for us, and extra flushes reduce batching. We flush explicitly in production only when we need an error or a generated value before the end of the transaction, for example to catch a duplicate and translate it into a friendly response. In tests, flushing is normal, because the test transaction never commits.

7Conclusion

In this answer, we saw that save() does not send SQL straight away. It adds the entity to the persistence context, and Hibernate sends the INSERT at flush time, normally at commit. Because @DataJpaTest runs each test in a transaction that is rolled back, the flush never happens, the database never receives the duplicate row, and the unique constraint is never checked. Calling saveAndFlush() or entityManager.flush() inside the assertion fixes it, with the exception type depending on whether the call goes through Spring's translation. The IDENTITY strategy hides the issue because it forces an immediate insert, so it is better not to rely on it.

What to say in the interviewAbout 80 seconds aloud

Open with

The test fails because no SQL ever reaches the database. save on a new entity calls persist, and persist only puts the entity into the persistence context and schedules an insert.

Then, if they want more

Hibernate sends the INSERT when it flushes, which by default is at commit. @DataJpaTest is transactional and rolls back after every test, so there is no commit, no flush, and the unique constraint, which lives in the database, is never checked. If I turn on SQL logging I can see sequence calls but no inserts.

The fix is to flush inside the assertion: use saveAndFlush, or call flush on the EntityManager or TestEntityManager. Through the repository I expect DataIntegrityViolationException because of Spring's exception translation; a direct EntityManager flush throws Hibernate's ConstraintViolationException, which is a PersistenceException.

One detail that explains why the same test sometimes passes: with GenerationType.IDENTITY Hibernate must insert immediately to get the id, so the error appears on save itself, while with SEQUENCE the insert is delayed.

I would not rely on that; I would flush explicitly so the test does not depend on the id strategy, and I would make sure the constraint actually exists in the test schema, ideally from the real migrations.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6
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 "A @DataJpaTest saves an entity that violates a unique constraint, but the test that...": https://scrivio-interview-library.netlify.app/java/integration-testing/3bd68c7ca4/