EN VI

Java - Is it guaranteed that constraint violation is flagged at the end of transactional block?

2024-03-11 11:30:05
Java - Is it guaranteed that constraint violation is flagged at the end of transactional block?

I’m using Postgres and have a transactional method defined as follows:

@Entity
public class SomeEntity {
    // …
}

@Transactional(isolation = READ_COMMITED)
public void persistUniqueAndSendEmail() {
    SomeEntity e = // …
    // Persis the entity to Postgres with a unique constraint that may fail

    // Once the entity is persisted send the notification email
}

With READ_COMMITED isolation level is it possible that the unique constraint violation is thrown when the transaction is actually committed, not the actual sql statement is executed?

If so that would mean that the email can be sent, but the relevant changes are not persisted.

Solution:

The transaction doesnt finish until the end of the method. The save doesnt flush until the transaction finishing prompts it to. So yes, you could get a constraint violation that rolls back the save after the email is sent.

You could try calling saveAndFlush instead of save (see Difference between save and saveAndFlush in Spring data jpa). The flush forces the database call to occur, which will trigger any constraint violation.

But you dont want the transaction to fail for some other reason and have the email sent erroneously. The safe thing to do is make sure the transaction completes successfully, then send the email either in another service calling the transactional service, or in an AOP interceptor.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login