I’m currently encountering an issue with Spring JPA, where it fails to immediately throw an exception upon encountering a unique constraint violation in PostgreSQL.
Here’s the setup:
The client calls the WebApp, which then sends a gRPC call to one of the backend services for request processing.
Within the backend service, there’s a Service layer responsible for interacting with the database repository (which extends JpaRepository).
@Transactional(propagation = Propagation.MANDATORY)
public void save(EntityClass entityClass) {
try {
repository.save(entityClass);
} catch (DataIntegrityViolationException e) {
log.error("Data integrity violation while adding entity", e);
throw e;
}
}
The peculiar part is that neither the above try-catch block nor the one in the preceding layer catches the exception. Even worse, the backend service falsely informs the WebApp that everything is successfully saved, prompting the WebApp to return a 204 response to the client.
However, the unique constraint violation is only raised as an exception within the backend service container after responding to the WebApp. I also attempted using saveAndFlush()
, but it didn’t resolve the issue.
I do not have any settings related to the FlushModeType in this setup.
Also, I do not want to check for the entity’s existence before saving as that would be an extra DB call. I’m okay to take the exception instead of performance penalty
3