If you want to force the persistence provider to flush the EntityManager
before the transaction commits or rolls back you either need to manually flush it or use saveAndFlush(…)
on the JpaRepository
.
The reason for that is that in the auto-generated ID case, the persistence provider has to flush to be able to bind the ID to the Java object. In the case of manually assigned IDs there's simply no need to flush at any earlier point in time than on transaction end, hence the persistence provider avoids the database interaction.
Besides these technical details, I'd argue that relying on the persistence provider to do this kind of validation is architecturally problematic anyway. If the provider detects a violation you've essentially piped an invalid object through all kinds of business logic. To make sure you don't have to code that defensively (null checks each and everywhere) you could simply enforce the property to not be nullable by checking the value handed into a constructor or the setter. This way, you essentially know that, whenever you get an instance of the object, the value will never be null
, no matter if some third framework has been invoked, or some developer accidentally forgot to invoke it.