[Java Advanced] Detailed explanation of JDBC management transactions

Insert image description here

In database operations, transactions are a very important concept. Transactions can ensure that a series of database operations are either successfully executed or rolled back upon failure to maintain the consistency and integrity of the database. In Java, we can use JDBC to manage transactions. This article will introduce the method and sample code of JDBC transaction management in detail. At the same time, it will be explained in simple and clear language for basic beginners.

what is transaction

In a database, a transaction is a set of SQL operations that are treated as a single unit of work. Transactions have the following four key properties, often referred to as ACID properties:

  • Atomicity : Transactions are atomic, either all of them are executed successfully or all of them fail and are rolled back. If one of the operations fails, the entire transaction fails, leaving no partial modifications.

  • Consistency : The database moves from one consistent state to another consistent state before and after a transaction is executed. This means that transactions must follow the integrity constraints of the database, such as primary keys, unique constraints, etc.

  • Isolation : Multiple transactions can be executed concurrently, but they cannot interfere with each other. Modifications by one transaction are not visible to other transactions until they are committed.

  • Durability : Once a transaction is submitted successfully, its results will be permanently stored in the database and will not be lost even if the system fails.

JDBC transaction management

JDBC (Java Database Connectivity) is an API in Java for interacting with databases. JDBC provides a way to manage database transactions in Java programs.

Open transaction

To start a transaction in JDBC, you need to perform the following steps:

  1. Create a database connection (Connection) object.
  2. Set the connection's autocommit mode to false, which means transactions will not commit automatically.
  3. Execute a series of SQL operations within a transaction.
  4. Finally, depending on the success or failure of the operation, you choose to commit or rollback the transaction.

The following is a sample code that demonstrates how to start a JDBC transaction:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class TransactionExample {
    
    
    public static void main(String[] args) {
    
    
        String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "root";
        String password = "password";

        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
    
    
            // 关闭自动提交,开启事务
            connection.setAutoCommit(false);

            // 执行一系列数据库操作

            // 提交事务
            connection.commit();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
            // 发生异常,回滚事务
            connection.rollback();
        }
    }
}

In the above code, we setAutoCommit(false)turn off the auto-commit mode through the method, and then tryperform a series of database operations in the block. If an exception occurs, we catchcall rollback()the method in the block to roll back the transaction.

Commit and rollback transactions

In JDBC, to commit a transaction, you can use commit()the method, as shown in the example above. After a transaction is committed, all operations within it become part of the database.

If something goes wrong during a transaction, you can use rollback()the method to roll back the transaction, undoing any uncommitted changes, and restoring the database to the state it was in before the transaction started. In the above example, we catchcalled rollback()the method in the block to roll back the transaction.

Set transaction isolation level

In JDBC, you can set the isolation level of a transaction to control the degree to which multiple transactions interact with each other. JDBC supports the following four transaction isolation levels, from low to high:

  1. TRANSACTION_NONE : Transactions are not supported. Each SQL statement is automatically committed and will not be rolled back.

  2. TRANSACTION_READ_UNCOMMITTED : Allows reading uncommitted data changes. This means that one transaction can see another transaction's uncommitted data.

  3. TRANSACTION_READ_COMMITTED : Only committed data changes are allowed to be read. This is the default isolation level for most database systems.

  4. TRANSACTION_REPEATABLE_READ : Ensures that the data does not change when the same data is read multiple times in a transaction. However, other transactions can still insert new data.

  5. TRANSACTION_SERIALIZABLE : The highest isolation level, ensuring complete isolation between transactions and not allowing concurrent access.

To set the transaction isolation level, you can use setTransactionIsolation()the method. Here is a sample code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class TransactionIsolationExample {
    
    
    public static void main(String[] args) {
    
    
        String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "root";
        String password = "password";

        try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password)) {
    
    
            // 设置事务隔离级别为 TRANSACTION_SERIALIZABLE
            connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

            // 关闭自动提交,开启事务
            connection.setAutoCommit(false);

            // 执行一系列数据库操作

            // 提交事务
            connection.commit();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
            // 发生异常,回滚事务
            connection.rollback();
        }
    }
}

In the above code, we setTransactionIsolation()set the transaction isolation level to Connection.TRANSACTION_SERIALIZABLEthe highest level of isolation through the method.

Matters needing attention

There are some important considerations when using JDBC for transaction management:

  1. Close the connection : Be sure to close the database connection after the transaction ends. You can use try-with-resources or close the connection in a finally block to ensure that resources are released correctly.

  2. Exception handling : Capture and handle SQLException that may occur. Roll back the transaction in the catch block with appropriate error handling.

  3. Commit frequency : Choose when to commit transactions as needed. Instead of committing after every SQL statement, decide the commit point based on business needs.

  4. Isolation level : Choose an appropriate transaction isolation level to balance concurrency and consistency. Higher isolation levels result in performance degradation, so trade them off based on your application's needs.

  5. Testing and debugging : Transactions are fully tested and debugged before production to ensure they work properly.

Conclusion

Transaction management is an integral part of database operations, ensuring data consistency and integrity. Through JDBC, you can easily start, commit, and rollback transactions, and you can control the isolation level of transactions to meet the needs of different applications. I hope this article helps you better understand transaction management in JDBC.

Author information

Author: Fanyi
CSDN: https://techfanyi.blog.csdn.net
Nuggets: https://juejin.cn/user/4154386571867191

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/133563151