Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

The transaction mechanism in JPA is a powerful tool that ensures atomicity and data integrity by either committing all changes or rolling them back in case of an exception. However, there are scenarios where continuing with the transaction after encountering an exception, without rolling back the data changes, becomes necessary.

In this article, we’ll delve into various use cases where this situation arises. Additionally, we’ll explore potential solutions for such cases.

2. Determining the Issue

We have two main cases where exceptions may occur within the transaction. Let’s start by understanding them.

2.1. Rollback the Transaction After Exception in the Service Layer

The first place where we may encounter the rollback is in the service layer, where an external exception could affect the database changes.

Let’s examine this scenario more closely using the following example. First things first, let’s add the InvoiceEntity, which serves as our data model:

@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = "serialNumber")})
public class InvoiceEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String serialNumber;
    private String description;
    //Getters and Setters
}

Here, we have an internal ID that will be generated automatically, a serial number that needs to be unique across the system, and a description.

Now, let’s create the InvoiceService responsible for transactional operations on our invoices:

@Service
public class InvoiceService {
    @Autowired
    private InvoiceRepository repository;
    
    @Transactional
    public void saveInvoice(InvoiceEntity invoice) {
        repository.save(invoice);
        sendNotification();
    }
    
    private void sendNotification() {
        throw new NotificationSendingException("Notification sending is failed");
    }
}

Inside the saveInvoice() method, we added the logic that should transactionally save the invoice and send the notification about it. Unfortunately, during the notification-sending process, we’ll face the exception:

public class NotificationSendingException extends RuntimeException {
    public NotificationSendingException(String text) {
        super(text);
    }
}

We don’t have anything specifically implemented, just a RuntimeException exception. Let’s observe the behavior in this scenario:

@Autowired
private InvoiceService service;

@Test
void givenInvoiceService_whenExceptionOccursDuringNotificationSending_thenNoDataShouldBeSaved() {
    InvoiceEntity invoiceEntity = new InvoiceEntity();
    invoiceEntity.setSerialNumber("#1");
    invoiceEntity.setDescription("First invoice");

    assertThrows(
        NotificationSendingException.class,
        () -> service.saveInvoice(invoiceEntity)
    );

    List<InvoiceEntity> entityList = repository.findAll();
    Assertions.assertTrue(entityList.isEmpty());
}

We invoked the saveInvoice() method from the service, encountered the NotificationSendingException, and, as expected, all the database changes were rolled back.

2.2. Rollback the Transaction After Exception in the Persistence Layer

Another case where we can face the implicit rollback is in the persistence layer.

We may assume that if we caught the exception from databases we’re able to continue our logic of data manipulation within the same transaction. But that’s not the case. Let’s create a saveBatch() method in our InvoiceRepository and try to reproduce the issue:

@Repository
public class InvoiceRepository {
    private final Logger logger = LoggerFactory.getLogger(
      com.baeldung.continuetransactionafterexception.InvoiceRepository.class);

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    public void saveBatch(List<InvoiceEntity> invoiceEntities) {
        invoiceEntities.forEach(i -> entityManager.persist(i));
        try {
            entityManager.flush();
        } catch (Exception e) {
            logger.error("Exception occured during batch saving, save individually", e);

            invoiceEntities.forEach(i -> {
                try {
                    save(i);
                } catch (Exception ex) {
                    logger.error("Problem saving individual entity {}", i.getSerialNumber(), ex);
                }
            });
        }
    }
}

In the saveBatch() method, we attempt to save the list of objects using a single flush operation. If any exception occurs during this operation, we catch it and proceed to save each object individually. Let’s implement the save() method in the following way:

@Transactional
public void save(InvoiceEntity invoiceEntity) {
    if (invoiceEntity.getId() == null) {
        entityManager.persist(invoiceEntity);
    } else {
        entityManager.merge(invoiceEntity);
    }

    entityManager.flush();
    logger.info("Entity is saved: {}", invoiceEntity.getSerialNumber());
}

We handle each exception by catching and logging it to avoid triggering a transaction rollback. Let’s call it and see how it works:

@Test
void givenInvoiceRepository_whenExceptionOccursDuringBatchSavingInternally_thenNoDataShouldBeSaved() {
    List<InvoiceEntity> testEntities = new ArrayList<>();

    InvoiceEntity invoiceEntity = new InvoiceEntity();
    invoiceEntity.setSerialNumber("#1");
    invoiceEntity.setDescription("First invoice");
    testEntities.add(invoiceEntity);

    InvoiceEntity invoiceEntity2 = new InvoiceEntity();
    invoiceEntity2.setSerialNumber("#1");
    invoiceEntity.setDescription("First invoice (duplicated)");
    testEntities.add(invoiceEntity2);

    InvoiceEntity invoiceEntity3 = new InvoiceEntity();
    invoiceEntity3.setSerialNumber("#2");
    invoiceEntity.setDescription("Second invoice");
    testEntities.add(invoiceEntity3);

    UnexpectedRollbackException exception = assertThrows(UnexpectedRollbackException.class,
      () -> repository.saveBatch(testEntities));
    assertEquals("Transaction silently rolled back because it has been marked as rollback-only",
      exception.getMessage());

    List<InvoiceEntity> entityList = repository.findAll();
    Assertions.assertTrue(entityList.isEmpty());
}

We’ve prepared a list of invoices, two of which violate the unique constraint on the serial number field. When attempting to save this list of invoices, we encounter the UnexpectedRollbackException, and no items are saved in the database. This occurs because, after the first exception, our transaction was marked as rollback only, preventing any further commits from taking place within it.

3. Use noRollbackFor Property of the @Transactional Annotation

For the cases where the exception happens outside the JPA calls, we can use the noRollbackFor property of the @Transactional annotation to retain the database changes if some expected exception occurred in the same transaction.

Let’s modify our saveInvoiceWithoutRollback() method in the InvoiceService class:

@Transactional(noRollbackFor = NotificationSendingException.class)
public void saveInvoiceWithoutRollback(InvoiceEntity entity) {
    repository.save(entity);
    sendNotification();
}

Now, let’s call this method and see how the behavior is changed:

@Test
void givenInvoiceService_whenNotificationSendingExceptionOccurs_thenTheInvoiceBeSaved() {
    InvoiceEntity invoiceEntity = new InvoiceEntity();
    invoiceEntity.setSerialNumber("#1");
    invoiceEntity.setDescription("We want to save this invoice anyway");

    assertThrows(
      NotificationSendingException.class,
      () -> service.saveInvoiceWithoutRollback(invoiceEntity)
    );

    List<InvoiceEntity> entityList = repository.findAll();
    Assertions.assertTrue(entityList.contains(invoiceEntity));
}

As expected, we got NotificationSendingException. However, the invoice was saved successfully in the database.

4. Use Transactions Manually

In cases where we encounter rollback in the persistence layer, we can manually control transactions to ensure that data is saved even if an exception occurs.

Let’s inject the EntityManagerFactory into our InvoiceRepository and create a method to create the EntityManager:

@Autowired
private EntityManagerFactory entityManagerFactory;

private EntityManager em() {
    return entityManagerFactory.createEntityManager();
}

We’ll not use shared EntityManager in this example since it doesn’t allow us to manipulate transactions manually. Now, let’s implement the saveBatchUsingManualTransaction() method:

public void saveBatchUsingManualTransaction(List<InvoiceEntity> testEntities) {
    EntityTransaction transaction = null;
    try (EntityManager em = em()) {
        transaction = em.getTransaction();
        transaction.begin();
        testEntities.forEach(em::persist);
        try {
            em.flush();
        } catch (Exception e) {
            logger.error("Duplicates detected, save individually", e);
            transaction.rollback();
            testEntities.forEach(t -> {
                EntityTransaction newTransaction = em.getTransaction();
                try {
                    newTransaction.begin();
                    saveUsingManualTransaction(t, em);
                } catch (Exception ex) {
                    logger.error("Problem saving individual entity <{}>", t.getSerialNumber(), ex);
                    newTransaction.rollback();
                } finally {
                    commitTransactionIfNeeded(newTransaction);
                }
            });
        }
    } finally {
        commitTransactionIfNeeded(transaction);
    }
}

Here, we begin the transaction,  persist all the items, flush the changes, and commit the transaction. If any exception occurs, we roll back the current transaction and save each item individually using separate transactions. In saveUsingManualTransaction(), we’ve implemented the next code:

private void saveUsingManualTransaction(InvoiceEntity invoiceEntity, EntityManager em) {
    if (invoiceEntity.getId() == null) {
        em.persist(invoiceEntity);
    } else {
        em.merge(invoiceEntity);
    }

    em.flush();
    logger.info("Entity is saved: {}", invoiceEntity.getSerialNumber());
}

We added the same logic as in the save() method, but we used entity manager from the method parameters. In the commitTransactionIfNeeded(), we’ve implemented the commit logic:

private void commitTransactionIfNeeded(EntityTransaction newTransaction) {
    if (newTransaction != null && newTransaction.isActive()) {
        if (!newTransaction.getRollbackOnly()) {
            newTransaction.commit();
        }
    }
}

Finally, let’s use the new repository method and see how it handles exceptions:

@Test
void givenInvoiceRepository_whenExceptionOccursDuringBatchSavingInternally_thenDataShouldBeSavedInSeparateTransaction() {
    List<InvoiceEntity> testEntities = new ArrayList<>();

    InvoiceEntity invoiceEntity1 = new InvoiceEntity();
    invoiceEntity1.setSerialNumber("#1");
    invoiceEntity1.setDescription("First invoice");
    testEntities.add(invoiceEntity1);

    InvoiceEntity invoiceEntity2 = new InvoiceEntity();
    invoiceEntity2.setSerialNumber("#1");
    invoiceEntity1.setDescription("First invoice (duplicated)");
    testEntities.add(invoiceEntity2);

    InvoiceEntity invoiceEntity3 = new InvoiceEntity();
    invoiceEntity3.setSerialNumber("#2");
    invoiceEntity1.setDescription("Second invoice");
    testEntities.add(invoiceEntity3);

    repository.saveBatchUsingManualTransaction(testEntities);

    List<InvoiceEntity> entityList = repository.findAll();
    Assertions.assertTrue(entityList.contains(invoiceEntity1));
    Assertions.assertTrue(entityList.contains(invoiceEntity3));
}

We called the batch method with the invoices list that contains duplicates. But now, we can see that two of three invoices were successfully saved.

5. Split the Transaction

We can get the same behavior as in the previous section using @Transactional annotated methods. The only issue is we can not call all these methods inside the one bean, as we did when using transactions manually. But, we can create two @Transactional annotated methods in our InvoiceRepository and call them from our client code. Let’s implement the saveBatchOnly() method:

@Transactional
public void saveBatchOnly(List<InvoiceEntity> testEntities) {
    testEntities.forEach(entityManager::persist);
    entityManager.flush();
}

Here, we’ve added only the batch-saving implementation. The save() method is reused from the examples in previous sections. Now, let’s see how we can use these two methods:

@Test
void givenInvoiceRepository_whenExceptionOccursDuringBatchSaving_thenDataShouldBeSavedUsingSaveMethod() {
    List<InvoiceEntity> testEntities = new ArrayList<>();

    InvoiceEntity invoiceEntity1 = new InvoiceEntity();
    invoiceEntity1.setSerialNumber("#1");
    invoiceEntity1.setDescription("First invoice");
    testEntities.add(invoiceEntity1);

    InvoiceEntity invoiceEntity2 = new InvoiceEntity();
    invoiceEntity2.setSerialNumber("#1");
    invoiceEntity1.setDescription("First invoice (duplicated)");
    testEntities.add(invoiceEntity2);

    InvoiceEntity invoiceEntity3 = new InvoiceEntity();
    invoiceEntity3.setSerialNumber("#2");
    invoiceEntity1.setDescription("Second invoice");
    testEntities.add(invoiceEntity3);

    try {
        repository.saveBatchOnly(testEntities);
    } catch (Exception e) {
        testEntities.forEach(t -> {
            try {
                repository.save(t);
            } catch (Exception e2) {
                System.err.println(e2.getMessage());
            }
        });
    }

    List<InvoiceEntity> entityList = repository.findAll();
    Assertions.assertTrue(entityList.contains(invoiceEntity1));
    Assertions.assertTrue(entityList.contains(invoiceEntity3));
}

We save the entity list that contains duplicates using the saveBatchOnly() method. If any exception occurs, we use the save() method in the loop to save all the items individually if it’s possible. Finally, we can see that all expected items were saved.

6. Conclusion

Transactions are a powerful mechanism that enables us to perform atomic operations. Rollback is the expected behavior for failed transactions. However, in certain scenarios, we may need to proceed with our work despite the failure and ensure that our data is saved. We’ve reviewed various approaches to achieve this. We can choose the one that best suits our specific situation.

As usual, the full source code can be found over on GitHub.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.