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. Introduction

In this tutorial, we’ll implement transaction-based routing with Spring, sending write operations to a primary database and read-only operations to a replica. This is a common pattern in applications that use database replication to scale read speeds.

2. Why Route Transactions?

Without routing, every query hits the same database. This might become a bottleneck as traffic grows, so replication helps by maintaining replicas that mirror the primary database. This strategy increases read speeds, but the application still needs to know where to send each query. The approach we’ll use lets the transaction metadata decide automatically:
Transactional Service LayerUsing Spring’s AbstractRoutingDataSource, combined with the @Transactional annotation’s readOnly flag, we intercept every connection request and direct it to the suitable database.

3. Scenario Setup

Let’s start with a simple entity and a repository for the examples. This layer doesn’t need any special configuration.

3.1. Creating the Entity

Let’s start with an Order entity with basic properties. We explicitly set the generation strategy to IDENTITY so the database’s auto-increment column provides the ID:

@Entity
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String description;

    // default getters and setters and constructors
}

3.2. Creating the Repository

Next, we’ll create a Spring Data repository:

public interface OrderRepository
  extends JpaRepository<Order, Long> {
}

We now have everything we need to implement our routing datasource.

4. Implementing the Routing DataSource

We’ll extend AbstractRoutingDataSource to decide which DataSource to use based on the current transaction.

4.1. Defining the DataSource Types

First, let’s create an enum to represent our DataSource types when wiring up our configuration:

public enum DataSourceType {
    READ_WRITE, READ_ONLY
}

We’ll use READ_WRITE as the lookup key for the primary DataSource (where all inserts, updates, and deletes go) and READ_ONLY for the replica (used exclusively for select queries).

4.2. Creating the Routing Logic

Now, we’ll extend AbstractRoutingDataSource and override determineCurrentLookupKey(). This method checks whether the current transaction is read-only via TransactionSynchronizationManager:

public class TransactionRoutingDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        boolean readOnly = TransactionSynchronizationManager
          .isCurrentTransactionReadOnly();

        if (readOnly) {
            return DataSourceType.READ_ONLY;
        }

        return DataSourceType.READ_WRITE;
    }
}

Spring calls this method when a connection is needed, so we’ll use it for routing the request to either the primary or the replica.

5. Configuring the DataSources

We need to define the properties for both data sources, then wire them as beans. Note that this setup only controls which connection is used for a given transaction. Nothing in the routing layer prevents a write from being issued to the replica connection, since this enforcement is configured at the database level.

In the real world, that means the replica user is typically granted only SELECT privileges, or the replica database itself is configured to reject writes.

5.1. Defining the Application Properties

Let’s use the “spring.datasource” prefix to define connection properties in application.properties:

spring.datasource.readwrite.url=jdbc:h2:mem:primary;DB_CLOSE_DELAY=-1
spring.datasource.readwrite.username=sa
spring.datasource.readwrite.driverClassName=org.h2.Driver

spring.datasource.readonly.url=jdbc:h2:mem:replica;DB_CLOSE_DELAY=-1
spring.datasource.readonly.username=sa
spring.datasource.readonly.driverClassName=org.h2.Driver

Each data source points to its own in-memory H2 database. We set DB_CLOSE_DELAY to -1 so these aren’t dropped when the last connection closes.

5.2. Wiring the Configuration Beans

Because we’re defining a custom DataSource bean, Spring Boot’s JPA auto-configuration isn’t used. That means OrderRepository won’t have an EntityManagerFactory or TransactionManager unless we explicitly declare them. The @EnableJpaRepositories annotation lets us point the repository scanner at the beans we’ll define in this class:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
  basePackageClasses = OrderRepository.class,
  entityManagerFactoryRef = "routingEntityManagerFactory",
  transactionManagerRef = "routingTransactionManager"
)
public class DataSourceConfiguration {

    // ...
}

The basePackageClasses attribute extracts the package name from the class we provide for component scanning. So that it can scan everything we need, OrderRepository and Order must be in the same package.

We start by creating both DataSource beans from their respective properties prefixes. First, reading “spring.datasource.readwrite.*” properties:

@Bean
@ConfigurationProperties("spring.datasource.readwrite")
public DataSourceProperties readWriteProperties() {
    return new DataSourceProperties();
}

Then, reading “spring.datasource.readonly.*” properties:

@Bean 
@ConfigurationProperties("spring.datasource.readonly") 
public DataSourceProperties readOnlyProperties() { 
    return new DataSourceProperties();
}

Next, we build the actual DataSource instances. First, for the read-write source:

@Bean
public DataSource readWriteDataSource() {
    return readWriteProperties()
      .initializeDataSourceBuilder()
      .build();
}

Then, for the read-only source:

@Bean
public DataSource readOnlyDataSource() {
    return readOnlyProperties()
      .initializeDataSourceBuilder()
      .build();
}

5.3. Configuring Our TransactionRoutingDataSource

Now, we wire the routing DataSource in a TransactionRoutingDataSource bean:

@Bean
public TransactionRoutingDataSource routingDataSource() {
    TransactionRoutingDataSource routingDataSource =
      new TransactionRoutingDataSource();

    // ...

    return routingDataSource;
}

We’ll register both targets in a map, which we’ll use when calling setTargetDataSources():

Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put(DataSourceType.READ_WRITE, readWriteDataSource());
dataSourceMap.put(DataSourceType.READ_ONLY, readOnlyDataSource());

routingDataSource.setTargetDataSources(dataSourceMap);
routingDataSource.setDefaultTargetDataSource(readWriteDataSource());

We also call setDefaultTargetDataSource(), which defines the fallback to use when, for example, code runs outside a transaction.

5.4. Defining a Lazy DataSource

Since JPA acquires a connection before the transaction synchronization sets the read-only flag, we need to wrap our routing DataSource in a LazyConnectionDataSourceProxy. This way, the actual connection is deferred until the first SQL statement:

@Bean
@Primary
public DataSource dataSource() {
    return new LazyConnectionDataSourceProxy(routingDataSource());
}

We mark this bean with @Primary so that when auto-wiring a DataSource, there’s no chance the non-lazy routingDataSource() is used. Then, we configure an EntityManagerFactory to use our lazy proxy. LocalContainerEntityManagerFactoryBean is the standard choice when managing the JPA configuration manually, as it integrates with Spring’s lifecycle:

@Bean
public LocalContainerEntityManagerFactoryBean routingEntityManagerFactory(
  EntityManagerFactoryBuilder builder) {
    return builder
      .dataSource(dataSource())
      .packages(OrderRepository.class)
      .build();
}

We also need a TransactionManager wired to our factory. We return a JpaTransactionManager so that @Transactional methods propagate the transaction manager’s readOnly flag to our routing logic:

@Bean
public PlatformTransactionManager routingTransactionManager(
  LocalContainerEntityManagerFactoryBean routingEntityManagerFactory) {
    return new JpaTransactionManager(
      Objects.requireNonNull(routingEntityManagerFactory.getObject()));
}

After all this configuration, we’re ready to get to the service layer.

6. Creating the Service Layer

We’ll create a service that uses the @Transactional annotation to control routing:

@Service
public class OrderService {

    @Autowired
    OrderRepository orderRepository;

    // ...
}

Methods annotated with readOnly = true are routed to the replica, while other transactions go to the primary DataSource:

@Transactional
public Order save(Order order) {
    return orderRepository.save(order);
}

@Transactional(readOnly = true)
public List<Order> findAllReadOnly() {
    return orderRepository.findAll();
}

@Transactional
public List<Order> findAllReadWrite() {
    return orderRepository.findAll();
}

In this example, we have a find method for each DataSource. This will be useful later in our tests.

7. Setting up the Tests

In a real-life scenario, a replica continuously syncs data from the primary. But to keep tests simple, we’ll keep them unsynchronized. We’ll use this isolation to assert that routing is working correctly.

So, in our case, if a read-only query returns data written by a read-write transaction, we know it’s hitting the primary rather than the replica.

Let’s set up our test class:

@SpringBootTest
class TransactionRoutingIntegrationTest {

    @Autowired
    OrderService orderService;

    // ...
}

First, we verify that a read-write transaction stays on the primary database, so a saved order is immediately visible:

@Test
void whenSaveAndReadWithReadWrite_thenFindsOrder() {
    Order saved = orderService.save(new Order("laptop"));

    List<Order> result = orderService.findAllReadWrite();

    assertThat(result)
      .anyMatch(o -> o.getId().equals(saved.getId()));
}

Then, we confirm that a read-only transaction is routed to the replica. Because the replica is a separate, unsynchronized database, it can’t access an order saved to the primary DataSource:

@Test
void whenSaveAndReadWithReadOnly_thenOrderNotFound() {
    Order saved = orderService.save(new Order("keyboard"));

    List result = orderService.findAllReadOnly();

    assertThat(result)
      .noneMatch(o -> o.getId().equals(saved.getId()));
}

We explicitly check that findAllReadOnly() doesn’t return the saved order’s ID, verifying that this specific order wasn’t routed to the replica.

8. Considerations

Let’s go over a few practical aspects to keep in mind when using this routing pattern.

8.1. Replication Lag

There’s a delay between a write to the primary and its propagation to the replica. The duration of the delay depends on our infrastructure.

So, for time-sensitive flows (such as writing an entity and immediately reading it back), routing the read to the replica may return stale data. In cases like this, it’s safer to run both operations within a single read-write transaction.

8.2. Nested Transactions

With Spring’s default propagation, a @Transactional(readOnly = true) method called from within a @Transactional(readOnly = false) method uses the existing transaction. This means only the first transaction created takes effect, ignoring any other flags in subsequent @Transactional methods, so the query still goes to the primary database. To actually route the inner call to the replica, we’d need Propagation.REQUIRES_NEW to suspend the outer transaction and start a read-only one.

Also note that if both methods are in the same bean, Spring won’t intercept the internal call.

8.3. Multiple Read Replicas

It’s also possible to use more than one read replica to distribute traffic. One approach is to extend our routing logic to rotate between them by using a list of read-only DataSources and selecting one using a round-robin implementation in determineCurrentLookupKey(), but that’s out of scope for this article.

A more robust approach is to delegate read-only connections to a load-balanced connection URL. There are many production-ready alternatives for this, like PgBouncer or ProxySQL, depending on our infrastructure.

9. Conclusion

In this article, we implemented transaction-based DataSource routing with Spring using AbstractRoutingDataSource. We saw how to separate read-write and read-only traffic, why LazyConnectionDataSourceProxy is required for correct routing, and how to verify the behavior with integration tests.

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.

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