This article has participated in the third “topic writing” track of the Denver Creators Training Camp. For details, check out: Digg Project | Creators Training Camp third is ongoing, “write” to make a personal impact.

Database transaction

Database transaction is a logical unit in the execution of database management system, which consists of a series of database operations. When a transaction is committed to the DATABASE management system, the system needs to ensure that all operations in the transaction are successful and the results are permanently stored in the database. If the operation does not complete successfully, all operations are rolled back to the state before the transaction was executed.

Database transactions exist for two purposes:

  1. Provides a way for a sequence of database operations to recover from a failure to a normal state, while providing a way for the database to remain consistent even in an abnormal state.
  2. When multiple applications concurrently access a database, an isolation method can be provided between these applications to prevent their operations from interfering with each other.

For example, if Joe sends 100 yuan to Li Si through the banking system, the system needs to perform at least two operations in the database:

  1. Zhang SAN’s account was reduced by 100 yuan
  2. Li Si’s account is increased by 100 yuan

A database transaction ensures that both operations succeed or fail without causing $100 to appear or disappear.

Database transactions typically have four properties, known as ACID properties:

  • Atomicity: The transaction is executed as a whole, and all or none of the operations on the database contained within it are executed.
  • Consistency: Transactions should ensure that the state of a database changes from one consistent state to another. That is, the data in the database should meet integrity constraints.
  • Isolation: When multiple transactions are executed concurrently, the execution of one transaction should not affect the execution of other transactions.
  • Durability: Modifications to the database by committed transactions should be permanently saved in the database.

JDBC transaction

JDBC is short for Java Database Connectivity, is the Java language standard client program access to relational Database application program interface.

The steps for manipulating transactions using JDBC are usually as follows (the code contains only the key steps) :

Connection connection
try { 
    // Get the database connection
    connection = getConnection();
    // Start the transaction
    connection.setAutoCommit(false);
    // Perform database operations.// Commit the transaction
    connection.commit()
} catch (SQLException ex) {
    // Handle exceptions.// Rollback the transaction
    connection.rollback()
} finally {
    // Close the connection
    connection.close()
}
Copy the code

By default, JDBC commits every operation automatically. If transactions are enabled, you need to disable auto-commit. After performing a series of operations, finally commit the transaction manually. If an exception occurs, the transaction is rolled back manually. Finally, close the connection.

Spring’s transaction abstraction

The Spring Framework provides a consistent abstraction for transaction management. It is the key to the concept of transaction strategy, transaction strategy is defined by TransactionManager, one of the most core is PlatformTransactionManager excuse.

PlatformTransactionManager

PlatformTransactionManager interface definition is very abstract:

public interface PlatformTransactionManager extends TransactionManager {

	TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException;

	void commit(TransactionStatus status) throws TransactionException;

	void rollback(TransactionStatus status) throws TransactionException;

}
Copy the code
  • getTransactionMethods will be providedTransactionDefinitionArgument, returns oneTransactionStatusObject.
  • commitMethod to commit a transaction, requiredTransactionStatusAs a parameter.
  • rollbackMethod is used to roll back a transaction, requiredTransactionStatusAs a parameter.

TransactionStatus is an interface that describes the status of a transaction. TransactionDefinition defines the propagation behavior, isolation, timeout Settings, and whether a transaction is read-only.

TransactionDefinition

In the source code for the TransactionDefinition interface, include the following:

  • A series of constants representing propagation behavior
  • A series of constants representing isolation
  • A constant that represents the default timeout
  • Gets methods for propagation behavior, isolation, timeout, and whether read-only

That is, it defines the propagation behavior of a transaction, isolation, timeout, and whether it is read-only.

  • Propagation behavior refers to the method of running a transaction while it already exists in the transaction context, such as continuing to run in an existing transaction or suspending an existing transaction to create a new one.
  • Isolation refers to the degree to which the current transaction is isolated from the work of other transactions. For example, whether you can see committed writes from other transactions, etc.
  • Timeouts refer to how long a transaction runs before it times out and is automatically rolled back by the underlying transaction infrastructure.
  • The read-only property refers to whether the current transaction is a read-only transaction and is usually defined when a transaction only reads data but does not modify it.

Transmissibility of transactions

In TransactionDefinition, transaction propagation features include the following seven:

  • PROPAGATION_REQUIRED: Use the current transaction if there is one, otherwise create a new transaction. (Default value)
  • PROPAGATION_SUPPORTS: Transactions are not required.
  • PROPAGATION_MANDATORY: Throws an exception if there is no transaction currently.
  • PROPAGATION_REQUIRES_NEW: Creates a new transaction regardless of whether there is one currently.
  • PROPAGATION_NOT_SUPPORTED: Does not support transactions and runs in non-transactional mode.
  • PROPAGATION_NEVER: does not support transactions and throws an exception if one exists.
  • PROPAGATION_NESTEDCreate a transaction in the current transaction if there is one.

Isolation of transactions

There are five types of transaction isolation in TransactionDefinition:

The default is ISOLATION_DEFAULT, which directly uses the isolation level of the database. The other four:

Isolation, value Dirty read Unrepeatable read Phantom read
ISOLATION_READ_UNCOMMITTED 1 Square root Square root Square root
ISOLATION_READ_COMMITTED 2 x Square root Square root
ISOLATION_REPEATABLE_READ 4 x x Square root
ISOLATION_SERIALIZABLE 8 x x x

Use of Spring transaction abstractions

Programmatic transaction management

Programmatic transaction management is done primarily through TransactionTemplate.

Inject transactionTemplate into the component that needs the transaction:

@Autowired 
TransactionTemplate transactionTemplate;

@Autowired 
JdbcTemplate jdbcTemplate;
Copy the code

Complete transaction operation:

transactionTemplate.execute(new TransactionCallbackWithoutResult() { 
    @Override 
    protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) { 
        / / SQL executionjdbcTemplate.execute(SQL); }});Copy the code

Declarative transaction management

Declarative transaction management uses the Transactional annotation to accomplish this:

@Autowired 
JdbcTemplate jdbcTemplate; 

Rollback when a RuntimeException occurs
@Transactional(rollbackFor = RuntimeException.class) 
public void foo(a) throws RuntimeException { 
    jdbcTemplate.execute(SQL); 
    throw new RuntimeException(); 
}
Copy the code