When Hibernate ORM runs Bean Validation on entity lifecycle events, why might a @NotNull field be rejected before the INSERT in one service but fail as a database NOT NULL error in another, and how do you make it consistent?
answer
- which validation mode is in effect
- is a provider on the classpath
- listener on pre-insert and pre-update
- callback versus auto at startup
- jakarta versus org.hibernate exception
basics
~20 sHibernate validates entities through its own pre-insert and pre-update event listener only when a Bean Validation provider is present; the default mode, auto, silently skips otherwise. Set jakarta.persistence.validation.mode to callback so a missing provider fails startup.
solid answer
~40 sHibernate ORM, not Spring, runs this validation: at boot it registers `BeanValidationEventListener` for its pre-insert, pre-update, pre-upsert and pre-delete events and validates the entity just before the statement executes, usually at flush, or inside `persist()` when an IDENTITY id forces an early insert. The default `jakarta.persistence.validation.mode` is `auto`: if no provider such as Hibernate Validator is on the classpath, it logs at DEBUG and skips, so `@NotNull` compiles but nothing enforces it and the null reaches the database. That service sees `org.hibernate.exception.ConstraintViolationException`, which Spring turns into `DataIntegrityViolationException`; the other sees `jakarta.validation.ConstraintViolationException` with no SQL sent. I would add the provider to both, set the mode to `callback` so a missing provider fails startup, and check the per-operation group properties too.
code
properties · 2 linesspring.jpa.properties.jakarta.persistence.validation.mode=callback
spring.jpa.properties.jakarta.persistence.validation.group.pre-remove=jakarta.validation.groups.Defaultgo deeper
Recall that Hibernate itself can check Bean Validation annotations like @NotNull just before it writes an entity, separately from any validation in controllers.
Explain the listener on pre-insert and pre-update events, why the check runs at flush rather than at persist(), and the default groups for each operation.
Diagnose the split by comparing classpaths, the effective validation mode and group settings, read the exception package, and propose callback mode so a missing provider fails fast.
Weigh where invariants should be enforced across a fleet: provider validation for early, readable errors, database constraints for every writer, and shared configuration so services cannot drift.
## Who runs this validation **Bean Validation** (Jakarta Validation, usually implemented by Hibernate Validator) is a standard for declaring rules such as `@NotNull` or `@Size` on fields. Several layers can run those rules: Spring's method validation, Spring MVC's request binding, or code that calls a `Validator` by hand. This answer is about a fourth layer: **the persistence provider itself**. Hibernate ORM ships a listener, `BeanValidationEventListener`, that it registers on its own event system when the session factory is built. Nothing in the application calls it, and no Spring annotation switches it on. The listener is appended for these Hibernate events: - **pre-insert**: just before an `INSERT` for a new entity executes - **pre-update**: just before an `UPDATE` for a dirty entity executes - **pre-upsert**: just before an upsert executes - **pre-delete**: just before a `DELETE` executes - **pre-collection-update**: when an owned collection changes, the *owning* entity is validated with the update groups When a rule fails, the listener throws `jakarta.validation.ConstraintViolationException`, carrying every violation and a message naming the classes, the operation and the groups. No SQL for that row is sent. ## When it fires: flush, not the call The events fire when Hibernate executes the statement, not when your code calls `persist()` or a setter. Inserts and updates queue up in the persistence context and run at **flush**, which by default happens before commit or before a query that needs fresh data. So the exception usually surfaces from `flush()` or from the transaction commit, often lines away from the code that set the null. One common exception: with an **IDENTITY** primary key, Hibernate must run the `INSERT` to learn the id, so it executes the insert early, inside `persist()`, and the pre-insert validation fires there. In a Spring `@Transactional` method where the failure happens during commit, the caller commonly sees a `TransactionSystemException` with the validation exception further down the cause chain. ## The validation mode decides whether it runs at all The property `jakarta.persistence.validation.mode` controls activation. Hibernate accepts four values: | Value | Lifecycle validation | No provider on the classpath | |---|---|---| | `auto` (default) | on, if a provider bootstraps | skipped; a DEBUG log line only | | `callback` | on | startup fails | | `none` | off | nothing happens | | `ddl` (Hibernate-specific) | off; only schema constraints | startup fails | `callback` and `ddl` may be combined as a comma-separated list; `auto` and `none` must stand alone. The trap is `auto`. The `@NotNull` annotation lives in the small `jakarta.validation` API jar, which often arrives transitively, so the entity compiles. If no **provider** (the implementation, such as Hibernate Validator) is present, Hibernate cannot build a `ValidatorFactory`. In `auto` mode it treats that as a reason to skip activation, logs at DEBUG and moves on. Nothing warns you. ## The groups each operation validates Bean Validation rules belong to **groups**; a rule with no explicit group is in `jakarta.validation.groups.Default`. Hibernate picks groups per operation from these properties: - `jakarta.persistence.validation.group.pre-persist`: defaults to `Default` - `jakarta.persistence.validation.group.pre-update`: defaults to `Default` - `jakarta.persistence.validation.group.pre-remove`: defaults to **no group**, so deletes are not validated - `jakarta.persistence.validation.group.pre-upsert` (read by Hibernate): defaults to `Default` Each takes comma-separated class names, and an empty value means "validate nothing" for that operation. A service whose configuration points `pre-persist` at a custom group that does not contain the `@NotNull` rule will skip it, which is a second way to get the scenario. ## Diagnosing the two services 1. **Compare the classpaths.** Check whether the failing service has a provider at all. In Spring Boot, the JPA starter brings Hibernate ORM but not Hibernate Validator; the validation starter brings it. 2. **Compare the effective mode.** Look for `jakarta.persistence.validation.mode` (in Spring Boot, under `spring.jpa.properties.`) set to `none` or `ddl` in one service. 3. **Compare the group properties.** A custom `pre-persist` or `pre-update` group may leave out `Default`. 4. **Read the exception class.** The two failures share a simple name but not a package, as shown below. | Exception | Who raised it | What it means | |---|---|---| | `jakarta.validation.ConstraintViolationException` | Hibernate's validation listener | rule failed, no SQL sent | | `org.hibernate.exception.ConstraintViolationException` | the database, via JDBC | statement sent and rejected | Spring's exception translation turns the second into `DataIntegrityViolationException`. ## Making it consistent - Put the provider on every service that writes these entities. - Set the mode to `callback` so a missing provider **fails startup** instead of silently disabling validation. - Keep group overrides in shared configuration and include `Default` unless you mean to drop it. - Keep the database `NOT NULL` constraint as well. The listener only sees writes that pass through entity lifecycle events, so the column constraint is still the last line of defence.
- Why does @NotNull compile in the service where nothing enforces it?The annotation lives in the `jakarta.validation` API jar, which often arrives transitively. Hibernate checks that the API class is loadable, then tries to bootstrap a `ValidatorFactory`. With no provider, that bootstrap fails with a no-provider error, and in `auto` mode Hibernate treats it as a request to skip validation and logs only at DEBUG. Under `callback`, the same situation fails startup.
- Which groups does Hibernate validate for each operation, and how do you change them?Insert, update and upsert validate `jakarta.validation.groups.Default`; remove validates no group, so deletes go unchecked. Override with `jakarta.persistence.validation.group.pre-persist`, `pre-update` or `pre-remove` (Hibernate also reads `pre-upsert`), as comma-separated class names. An empty value disables validation for that operation, and a custom group that omits `Default` silently drops ungrouped rules like `@NotNull`.
- Why can a Spring caller see TransactionSystemException instead of the validation exception?Validation runs when the statement executes, which is often the flush at commit. When the commit fails that way, Hibernate typically reports it as a `RollbackException`, and Spring's `JpaTransactionManager` rethrows anything it cannot translate as `TransactionSystemException`. The `jakarta.validation.ConstraintViolationException` is still there, further down the cause chain. Calling `flush()` explicitly inside the method surfaces it earlier, from the flush itself.
Auto mode is like a site that books an inspector only if one happens to be free: when none is, building goes ahead uninspected and nobody is told. Callback mode refuses to open the site until an inspector is booked.
- Spring's @Validated or MVC's @Valid is what validates entities when they are saved.
- Validation always runs inside persist(), so a try block around persist() catches it.
- Without Hibernate Validator on the classpath, the default validation mode fails startup.
- Remove operations are validated against the Default group just like insert and update.
- Both failures throw the same ConstraintViolationException, so one catch block handles them.
- Setting the validation mode to ddl turns on validation before inserts and updates.