Spring 简明教程
Spring - Transaction Management
数据库事务是一系列操作,它们被当作一个工作单元执行。这些操作应要么全部完成,要么完全不产生任何效果。事务管理是面向 RDBMS 的企业应用程序的重要组成部分,以确保数据完整性和一致性。事务的概念可以用以下四项关键特性来描述 ACID −
A database transaction is a sequence of actions that are treated as a single unit of work. These actions should either complete entirely or take no effect at all. Transaction management is an important part of RDBMS-oriented enterprise application to ensure data integrity and consistency. The concept of transactions can be described with the following four key properties described as ACID −
-
Atomicity − A transaction should be treated as a single unit of operation, which means either the entire sequence of operations is successful or unsuccessful.
-
Consistency − This represents the consistency of the referential integrity of the database, unique primary keys in tables, etc.
-
Isolation − There may be many transaction processing with the same data set at the same time. Each transaction should be isolated from others to prevent data corruption.
-
Durability − Once a transaction has completed, the results of this transaction have to be made permanent and cannot be erased from the database due to system failure.
真正的 RDBMS 数据库系统将为每个事务保证所有四个特性。使用 SQL 向数据库发出的事务的简单视图如下 −
A real RDBMS database system will guarantee all four properties for each transaction. The simplistic view of a transaction issued to the database using SQL is as follows −
-
Begin the transaction using begin transaction command.
-
Perform various deleted, update or insert operations using SQL queries.
-
If all the operation are successful then perform commit otherwise rollback all the operations.
Spring 框架在不同基础事务管理 API 的基础上提供了抽象层。Spring 的事务支持旨在通过向 POJO 添加事务功能来提供 EJB 事务的替代方案。Spring支持基于编程和声明的事务管理。EJB 需要应用程序服务器,但 Spring 事务管理可以在不需要应用程序服务器的情况下实现。
Spring framework provides an abstract layer on top of different underlying transaction management APIs. Spring’s transaction support aims to provide an alternative to EJB transactions by adding transaction capabilities to POJOs. Spring supports both programmatic and declarative transaction management. EJBs require an application server, but Spring transaction management can be implemented without the need of an application server.
Local vs. Global Transactions
本地事务特定于单个事务性资源(例如 JDBC 连接),而全局事务则可以跨越多个事务性资源(例如分布式系统中的事务)。
Local transactions are specific to a single transactional resource like a JDBC connection, whereas global transactions can span multiple transactional resources like transaction in a distributed system.
当应用程序组件和资源位于一个站点时,本地事务管理在集中计算环境中可能很有用,并且事务管理仅涉及在单台机器上运行的本地数据管理器。本地事务更容易实现。
Local transaction management can be useful in a centralized computing environment where application components and resources are located at a single site, and transaction management only involves a local data manager running on a single machine. Local transactions are easier to be implemented.
在所有资源都分布在多个系统中的分布式计算环境中需要全局事务管理。在这种情况下,需要在本地和全局级别执行事务管理。跨多个系统执行分布式或全局事务,并且其执行要求全局事务管理系统和所有相关系统的所有本地数据管理程序之间的协调。
Global transaction management is required in a distributed computing environment where all the resources are distributed across multiple systems. In such a case, transaction management needs to be done both at local and global levels. A distributed or a global transaction is executed across multiple systems, and its execution requires coordination between the global transaction management system and all the local data managers of all the involved systems.
Programmatic vs. Declarative
Spring支持两种类型的事务管理−
Spring supports two types of transaction management −
-
Programmatic transaction management − This means that you have to manage the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
-
Declarative transaction management − This means you separate transaction management from the business code. You only use annotations or XML-based configuration to manage the transactions.
声明性事务管理优于编程事务管理,尽管它不如编程事务管理灵活,而后者允许您通过代码控制事务。但作为一种横切关注点,声明性事务管理可以通过 AOP 方法模块化。Spring 通过 Spring AOP 框架支持声明性事务管理。
Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code. But as a kind of crosscutting concern, declarative transaction management can be modularized with the AOP approach. Spring supports declarative transaction management through the Spring AOP framework.
Spring Transaction Abstractions
Spring 事务抽象的关键由 org.springframework.transaction.PlatformTransactionManager 接口定义,如下所示 −
The key to the Spring transaction abstraction is defined by the org.springframework.transaction.PlatformTransactionManager interface, which is as follows −
public interface PlatformTransactionManager {
TransactionStatus getTransaction(TransactionDefinition definition);
throws TransactionException;
void commit(TransactionStatus status) throws TransactionException;
void rollback(TransactionStatus status) throws TransactionException;
}
Sr.No |
Method & Description |
1 |
TransactionStatus getTransaction(TransactionDefinition definition) This method returns a currently active transaction or creates a new one, according to the specified propagation behavior. |
2 |
void commit(TransactionStatus status) This method commits the given transaction, with regard to its status. |
3 |
void rollback(TransactionStatus status) This method performs a rollback of the given transaction. |
TransactionDefinition 是 Spring 中事务支持的核心接口,定义如下 −
The TransactionDefinition is the core interface of the transaction support in Spring and it is defined as follows −
public interface TransactionDefinition {
int getPropagationBehavior();
int getIsolationLevel();
String getName();
int getTimeout();
boolean isReadOnly();
}
Sr.No |
Method & Description |
1 |
int getPropagationBehavior() This method returns the propagation behavior. Spring offers all of the transaction propagation options familiar from EJB CMT. |
2 |
int getIsolationLevel() This method returns the degree to which this transaction is isolated from the work of other transactions. |
3 |
String getName() This method returns the name of this transaction. |
4 |
int getTimeout() This method returns the time in seconds in which the transaction must complete. |
5 |
boolean isReadOnly() This method returns whether the transaction is read-only. |
以下是隔离级别的可能值 −
Following are the possible values for isolation level −
Sr.No |
Isolation & Description |
1 |
TransactionDefinition.ISOLATION_DEFAULT This is the default isolation level. |
2 |
TransactionDefinition.ISOLATION_READ_COMMITTED Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur. |
3 |
TransactionDefinition.ISOLATION_READ_UNCOMMITTED Indicates that dirty reads, non-repeatable reads, and phantom reads can occur. |
4 |
TransactionDefinition.ISOLATION_REPEATABLE_READ Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur. |
5 |
TransactionDefinition.ISOLATION_SERIALIZABLE Indicates that dirty reads, non-repeatable reads, and phantom reads are prevented. |
以下是传播类型的可能值 −
Following are the possible values for propagation types −
Sr.No. |
Propagation & Description |
1 |
TransactionDefinition.PROPAGATION_MANDATORY Supports a current transaction; throws an exception if no current transaction exists. |
2 |
*TransactionDefinition.PROPAGATION_NESTED * Executes within a nested transaction if a current transaction exists. |
3 |
*TransactionDefinition.PROPAGATION_NEVER * Does not support a current transaction; throws an exception if a current transaction exists. |
4 |
*TransactionDefinition.PROPAGATION_NOT_SUPPORTED * Does not support a current transaction; rather always execute nontransactionally. |
5 |
TransactionDefinition.PROPAGATION_REQUIRED Supports a current transaction; creates a new one if none exists. |
6 |
TransactionDefinition.PROPAGATION_REQUIRES_NEW Creates a new transaction, suspending the current transaction if one exists. |
7 |
TransactionDefinition.PROPAGATION_SUPPORTS Supports a current transaction; executes non-transactionally if none exists. |
8 |
TransactionDefinition.TIMEOUT_DEFAULT Uses the default timeout of the underlying transaction system, or none if timeouts are not supported. |
事务状态接口为事务代码提供了一种简单的方法来控制事务执行和查询事务状态。
The TransactionStatus interface provides a simple way for transactional code to control transaction execution and query transaction status.
public interface TransactionStatus extends SavepointManager {
boolean isNewTransaction();
boolean hasSavepoint();
void setRollbackOnly();
boolean isRollbackOnly();
boolean isCompleted();
}
Sr.No. |
Method & Description |
1 |
boolean hasSavepoint() This method returns whether this transaction internally carries a savepoint, i.e., has been created as nested transaction based on a savepoint. |
2 |
boolean isCompleted() This method returns whether this transaction is completed, i.e., whether it has already been committed or rolled back. |
3 |
boolean isNewTransaction() This method returns true in case the present transaction is new. |
4 |
boolean isRollbackOnly() This method returns whether the transaction has been marked as rollback-only. |
5 |
void setRollbackOnly() This method sets the transaction as rollback-only. |