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

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

Database connections created with the JDBC API have a feature called auto-commit mode.

Turning this mode on can help eliminate boilerplate code needed for managing transactions. In spite of this, however, its purpose and how it influences transaction handling when executing SQL statements can sometimes be unclear.

In this article, we’ll discuss what auto-commit mode is and how to use it correctly for both automatic and explicit transaction management. We’ll also cover various problems to avoid when auto-commit is either on or off.

2. What Is JDBC Auto-Commit Mode?

Developers will not necessarily understand how to manage database transactions effectively when using JDBC. Thus, if handling transactions manually, developers may not start them where appropriate or not at all. The same problem applies to issuing commits or rollbacks where necessary.

To get around this problem, the auto-commit mode in JDBC provides a way to execute SQL statements with transaction management handled automatically by the JDBC driver.

Thus, the intention of auto-commit mode is to lift the burden from developers of having to manage transactions themselves. In this way, turning it on can make it easier to develop applications with the JDBC API. Of course, this only helps where it’s acceptable for data updates to be persisted immediately after each SQL statement completes.

3. Automatic Transaction Management When Auto-Commit Is True

JDBC drivers turn on auto-commit mode for new database connections by default. When it’s on, they automatically run each individual SQL statement inside its own transaction.

Besides using this default setting, we can also turn on auto-commit manually by passing true to the connection’s setAutoCommit method:

connection.setAutoCommit(true);

This way of switching it on ourselves is useful for when we’ve previously switched it off, but then later we need automatic transaction management restored.

Now that we’ve covered how to ensure that auto-commit is on, we’ll demonstrate that when set as such, JDBC drivers run SQL statements in their own transactions. That is, they automatically commit any data updates from each statement to the database right away.

3.1. Setting Up the Example Code

In this example, we’ll use the H2 in-memory database to store our data. To use it, we first need to define the Maven dependency:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>2.1.214</version>
</dependency>

To start with, let’s create a database table to hold details about people:

CREATE TABLE Person (
    id INTEGER not null,
    name VARCHAR(50),
    lastName VARCHAR(50),
    age INTEGER,PRIMARY KEY (id)
)

Next, we’ll create two connections to the database. We’ll use the first one to run our SQL queries and updates on the table. And we’ll use the second connection to test if updates have been made to that table:

Connection connection1 = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", "");
Connection connection2 = DriverManager.getConnection("jdbc:h2:mem:testdb", "sa", "");

Note, we need to use a separate connection to test for committed data. This is because if we run any select queries on the first connection, then they will see updates that haven’t been committed yet.

Now we’ll create a POJO to represent a database record that holds information about a person:

public class Person {

    private Integer id;
    private String name;
    private String lastName;
    private Integer age;

    // standard constructor, getters, and setters
}

To insert a record into our table, let’s create a method named insertPerson:

private static int insertPerson(Connection connection, Person person) throws SQLException {    
    try (PreparedStatement preparedStatement = connection.prepareStatement(
      "INSERT INTO Person VALUES (?,?,?,?)")) {
        
        preparedStatement.setInt(1, person.getId());
        preparedStatement.setString(2, person.getName());
        preparedStatement.setString(3, person.getLastName());
        preparedStatement.setInt(4, person.getAge());
        
        return preparedStatement.executeUpdate();
    }        
}     

We’ll then add a updatePersonAgeById method to update a specific record in the table:

private static void updatePersonAgeById(Connection connection, int id, int newAge) throws SQLException {
    try (PreparedStatement preparedStatement = connection.prepareStatement(
      "UPDATE Person SET age = ? WHERE id = ?")) {
        preparedStatement.setInt(1, newAge);
        preparedStatement.setInt(2, id);
        
        preparedStatement.executeUpdate();
    }
}

Lastly, let’s add a selectAllPeople method to select all records from the table. We’ll use this to check the results of our SQL insert and update statements:

private static List selectAllPeople(Connection connection) throws SQLException {
    
    List people = null;
    
    try (Statement statement = connection.createStatement()) {
        people = new ArrayList();
        ResultSet resultSet = statement.executeQuery("SELECT * FROM Person");

        while (resultSet.next()) {
            Person person = new Person();
            person.setId(resultSet.getInt("id"));
            person.setName(resultSet.getString("name"));
            person.setLastName(resultSet.getString("lastName"));
            person.setAge(resultSet.getInt("age"));
            
            people.add(person);
        }
    }
    
    return people;
}

With these utility methods now in place, we’ll test the effects of turning on auto-commit.

3.2. Running the Tests

To test our example code, let’s first insert a person into the table. Then after that, from a different connection, we’ll check that the database has been updated without us issuing a commit:

Person person = new Person(1, "John", "Doe", 45);
insertPerson(connection1, person);

List people = selectAllPeople(connection2);
assertThat("person record inserted OK into empty table", people.size(), is(equalTo(1)));
Person personInserted = people.iterator().next();
assertThat("id correct", personInserted.getId(), is(equalTo(1)));

Then, with this new record inserted into the table, let’s update the person’s age. Thereafter, we’ll check from the second connection that the change has been saved to the database without us needing to call commit:

updatePersonAgeById(connection1, 1, 65);

people = selectAllPeople(connection2);
Person personUpdated = people.iterator().next();
assertThat("updated age correct", personUpdated.getAge(), is(equalTo(65)));

Thus, we have verified with our tests that when the auto-commit mode is on, the JDBC driver implicitly runs every SQL statement in its own transaction. As such, we don’t need to call commit to persist updates to the database ourselves.

4. Explicit Transaction Management When Auto-Commit Is False

We need to disable auto-commit mode when we want to handle transactions ourselves and group multiple SQL statements into one transaction.

We do this by passing false to the connection’s setAutoCommit method:

connection.setAutoCommit(false);

When the auto-commit mode is off, we need to manually mark the end of each transaction by calling either commit or rollback on the connection.

We need to note, however, that even with auto-commit turned off, the JDBC driver will still automatically start a transaction for us when needed. For example, this happens before we run our first SQL statement, and also after each commit or rollback.

Let’s demonstrate that when we execute multiple SQL statements with auto-commit off, the resulting updates will only be saved to the database when we call commit.

4.1. Running the Tests

To start with, let’s insert the person record using the first connection. Then without calling commit, we’ll assert that we cannot see the inserted record in the database from the other connection:

Person person = new Person(1, "John", "Doe", 45);
insertPerson(connection1, person);

List<Person> people = selectAllPeople(connection2);
assertThat("No people have been inserted into database yet", people.size(), is(equalTo(0)));

Next, we’ll update the person’s age on that record. And as before, we’ll then assert without calling commit, that we still can’t select the record from the database using the second connection:

updatePersonAgeById(connection1, 1, 65);

people = selectAllPeople(connection2);
assertThat("No people have been inserted into database yet", people.size(), is(equalTo(0)));

To complete our testing, we’ll call commit and then assert that we can now see all the updates in the database using the second connection:

connection1.commit();

people = selectAllPeople(connection2);
Person personUpdated = people.iterator().next();
assertThat("person's age updated to 65", personUpdated.getAge(), is(equalTo(65)));

As we have verified in our tests above, when the auto-commit mode is off we need to manually call commit to persist our changes to the database. Doing so will save any updates from all the SQL statements we’ve executed since the start of our current transaction. That is either since we opened the connection if this is our first transaction, or otherwise after our last commit or rollback.

5. Considerations and Potential Problems

It can be convenient for us to run SQL statements with auto-commit turned on for relatively trivial applications. That is, where manual transaction control is not necessary. However, in more complex situations we should consider that when the JDBC driver handles transactions automatically, this may sometimes lead to unwanted side effects or problems.

One thing we need to consider is that when auto-commit is on it can potentially waste significant processing time and resources. This is because it causes the driver to run every SQL statement in its own transaction whether necessary or not.

For example, if we execute the same statement many times with different values, each call is wrapped in its own transaction. Therefore, this can lead to unnecessary execution and resource management overhead.

Thus in such cases, it’s usually better for us to turn auto-commit off and explicitly batch multiple calls to the same SQL statement into one transaction. In doing so, we’ll likely see a substantial improvement in application performance.

Something else to note is that it’s not advisable for us to switch auto-commit back on during an open transaction. This is because turning the auto-commit mode on mid-transaction will commit all pending updates to the database, whether the current transaction is complete or not. Thus, we should probably avoid doing this as it may lead to data inconsistencies.

6. Conclusion

In this article, we discussed the purpose of auto-commit mode in the JDBC API. We also covered how to enable both implicit and explicit transaction management by turning it on or off respectively. Lastly, we touched on various issues or problems to consider whilst using it.

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)