Tips to Understand the Difference Between Propagation.REQUIRED and REQUIRES_NEW

Tuanh.netTuanh.net
2 min read

1. What is Transaction Propagation in Spring?

Before diving into the differences, it's important to understand what transaction propagation is. In Spring, transaction propagation determines how a method should handle existing transactions. It dictates whether a method should run within an existing transaction, create a new transaction, or not run within a transaction at all.

1.1 Propagation.REQUIRED

Propagation.REQUIRED is the default propagation type in Spring. When a method is annotated with @Transactional(propagation = Propagation.REQUIRED), it means that the method should run within an existing transaction if one exists. If there is no existing transaction, a new one will be created.

Example:

@Service
public class MyService {

@Transactional(propagation = Propagation.REQUIRED)
public void requiredMethod() {
// Some database operations
}
}

In the example above, requiredMethod() will either join an existing transaction or start a new one if none exists.

1.2 Propagation.REQUIRES_NEW

Propagation.REQUIRES_NEW creates a new transaction, suspending any existing transaction. This means that even if there is an ongoing transaction, it will be paused, and a new transaction will be created for the method annotated with @Transactional(propagation = Propagation.REQUIRES_NEW).

Example:

@Service
public class MyService {

@Transactional(propagation = Propagation.REQUIRES_NEW)
public void requiresNewMethod() {
// Some database operations
}
}

In this case, requiresNewMethod() will always start a new transaction, regardless of whether a transaction already exists.

2. Differences Between Propagation.REQUIRED and Propagation.REQUIRES_NEW

Understanding the key differences between Propagation.REQUIRED and Propagation.REQUIRES_NEW is essential for making informed decisions in your transactional management.

2.1 Transaction Behavior

  • Propagation.REQUIRED: If there is an existing transaction, it will be joined. If not, a new transaction is started.
  • Propagation.REQUIRES_NEW: Always creates a new transaction, suspending any existing transaction.

Read more at : Tips to Understand the Difference Between Propagation.REQUIRED and REQUIRES_NEW

0
Subscribe to my newsletter

Read articles from Tuanh.net directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tuanh.net
Tuanh.net