eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LSD – NPI (cat=JPA)
announcement - icon

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

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)