Persistence top

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

>> CHECK OUT THE COURSE

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>1.4.200</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.

As always, the full source code of the examples can be found over on GitHub.

Persistence bottom
Get started with Spring Data JPA through the reference Learn Spring Data JPA course: >> CHECK OUT THE COURSE
Persistence footer banner
Comments are closed on this article!