1. Introduction Transaction characteristics
A transaction is a unit of concurrency control and is a user-defined sequence of operations. These operations are either done or not, and are an inseparable unit of work. A transaction binds a logically related set of operations so that the server maintains the integrity of the data. A transaction usually begins with a BEGIN transaction and ends with a commit or rollback. Commint represents the commit, which commits all operations of the transaction. Specifically, all updates to the data in a transaction are written back to the physical database on disk, and the transaction ends normally. Rollback represents a rollback, in which a transaction fails to proceed while the transaction is running, and the system undoes all completed operations on the database in the transaction, rolling back to the state in which the transaction started.
Atomicity (Atomic) changes to the data are either all executed or not executed at all.
Consistency (consistent) the data state remains consistent before and after the transaction executes.
Isolation (Isolated) processing of one transaction cannot affect the processing of another transaction.
The persistence (durable) transaction ends and its effect is persisted in the database.
2. Types of Java transactions
There are three types of Java transactions: JDBC Transaction, JTA (Java Transaction API) transaction, container transaction.
1. JDBC Transaction
The JDBC transaction is controlled with the Connection object. The JDBC Connection Interface (java.sql.Connection) provides two transaction modes: Autocommit and Manual commit. Java.sql.Connection provides the following methods of controlling transactions:
public void Setautocommit (Boolean)
public boolean getautocommit ()
public void commit ()
public void rollback ()
When using JDBC transaction demarcation, you can combine multiple SQL statements into a single transaction. One drawback of JDBC transactions is that the scope of a transaction is limited to a single database connection. A JDBC transaction cannot span multiple databases.
2. JTA (Java Transaction API) transaction
JTA is a high-level, unrelated, protocol-agnostic API that enables applications and application servers to access transactions using JTA.
JTA allows applications to perform distributed transactions-access and update data on two or more network computer resources, which can be distributed across multiple databases. The JTA support of the JDBC driver greatly enhances the data access capability.
If you plan to define transactions with JTA, you need a JDBC driver that implements the Javax.sql.XADataSource, Javax.sql.XAConnection, and Javax.sql.XAResource interfaces. A driver that implements these interfaces will be able to participate in the JTA transaction. A Xadatasource object is a factory of a Xaconnection object. Xaconnection S is a JDBC connection that participates in JTA transactions.
You will need to set up Xadatasource with the application server's administration tools. You can learn about the guidance from the application server and the JDBC driver documentation.
The Java EE application queries the data source with JNDI. Once the application finds the data source object, it calls Javax.sql.DataSource.getConnection () to get a connection to the database.
XA connections are not the same as non-XA connections. Be sure to remember that the XA connection participates in the JTA transaction. This means that the XA connection does not support the auto-commit feature of JDBC. Also, the application must not call Java.sql.Connection.commit () or Java.sql.Connection.rollback () on the XA connection.
Instead, applications should use Usertransaction.begin (), Usertransaction.commit (), and Sertransaction.rollback ().
3. Container Service
Container transactions are mainly provided by the Java EE Application Server, and the container transactions are mostly based on JTA, which is a jndi-based, fairly complex API implementation. Relative coding implements JTA transaction management, and we can accomplish the same function through the container transaction management mechanism (CMT) provided by the EJB container, which is provided by the Java EE Application Server. This allows us to simply specify which method to join the transaction, and once specified, the container will be responsible for the transaction management task. This is our way of doing civil work, because in this way we can exclude the transaction code from the logic code, and all the difficulties to the Java EE container to solve. Another benefit of using EJB CMT is that programmers do not have to care about the coding of the JTA API, but in theory we have to use EJBS.
4, three Java transaction differences
The limitations of JDBC transaction control are within a database connection, but they are simple to use.
JTA transactions are powerful, and transactions can span multiple databases or multiple DAO, and are more complex to use.
Container transactions, mainly refers to the Java EE Application Server provides transaction management, limited to the use of EJB applications.
5. Application Scenario
Java transaction control is an indispensable part of building the EE application, and it is very important for the whole application to choose what kind of transaction to apply. in general, the JDBC transaction can be selected in the case of a single JDBC connection connection, with the option to use JTA transactions across multiple connections or databases, and if EJB is used, consider using EJB container transactions
3. Spring Transaction Realization Source code Analysis
3.1 DAO Module
dao模块定义了数据库层的各种异常,其中异常的结构已经在spring-jdbc模块中介绍过了,在这里主要是dao的支持和异常的转译,其数据库支持和转译结构如下所示:
dao 支持
提供了对hibernate、jdbc,cci的支持。我们都想到熟悉,对cci可能有些陌生,下面的章节会讲到。
dao异常转译
PersistenceExceptionTranslationPostProcessor:自动将标示为@repository的bean的持久化异常进行转译。它增加一个PersistenceExceptionTranslationAdvisor来代理相应的已经存在的aop代理或者实现了目标接口的新产生的代理。它将本地资源异常转换为spring的DataAccessException及其子类上。
PersistenceExceptionTranslationAdvisor是一个spring aop的异常转译类,它应用到respository层或者dao层。它基于给定的PersistenceExceptionTranslator来将本地持久化异常转换为spring的DataAccessException族。
PersistenceExceptionTranslationInterceptor:一个aop 方法拦截器(MethodInterceptor).提供基于PersistenceExceptionTranslator的异常转换,它是PersistenceExceptionTranslator的代理,将运行时抛出的异常转换为spring 的DataAccessException族。
PersistenceExceptionTranslator spring集成其它数据获取技术(如jpa、toplink、jdo、hibernate等)抛出运行时异常的接口。
3.2 JCA module
1. cci模块
J2EE provides a jca (Java Connector Architecture) specification to standardize on the EIS (Enterprise Information System) access. This specification is divided into several different parts: the
SPI (Service provider interfaces) is the interface that the connector provider (connector provider) must implement. These interfaces comprise a resource adapter (resource adapter) that can be deployed on the Java EE Application Server. In this case, the server manages the connection pool (connection pooling), transactions, and security (managed mode). The application server is also responsible for managing configurations that are owned outside of the client application. The connector (connector) can also be used without the application server, in which case the application must be configured directly (unmanaged mode (non-managed)).
CCI (Common Client Interface) is an interface that an application uses to interact with the connector and communicate with the EIS. It also provides an API for local transaction demarcation.
Spring's support for CCI is intended to provide classes that access the CCI connector in a typical spring manner, and to effectively use spring's common resource and transaction management tools.
Note:
The client of the connector does not have to always use CCI. Some connectors expose their own APIs, providing only the JCA resource adapter (resource adapter) to use some system contracts of the Java EE container (contracts) (connection pooling (connection pooling), Global transactions, security). Spring does not provide special support for this type of connector-specific (connector-specific) API.
2. context模块
ResourceAdapterApplicationContext:一个jca ResourceAdapter的applicationContext实现,需要于jca的bootstrapContext一同初始化,最后传递到实现了BootstrapContextAware的spring 受管理bean。
@Overrideprotected voidPostprocessbeanfactory (Configurablelistablebeanfactory beanfactory)throwsbeansexception {beanfactory.addbeanpostprocessor (NewBootstrapcontextawareprocessor ( This. Bootstrapcontext)); Beanfactory.ignoredependencyinterface (Bootstrapcontextaware.class); Beanfactory.registerresolvabledependency (Bootstrapcontext.class, This. Bootstrapcontext); //JCA WorkManager resolved Lazily-may not be available.Beanfactory.registerresolvabledependency (WorkManager.class,NewObjectfactory<workmanager>() {@Override PublicWorkManager GetObject () {returnBootstrapcontext.getworkmanager (); } }); }
Bootstrapcontextawareprocessor: Passes Bootstrapcontext to the spring bean that implements the Bootstrapcontextaware interface. It is automatically registered in the internal bean factory.
Bootstrapcontextaware: The implementation class that needs to be notified of Bootstrapcontext.
Bootstrapcontext: Provides a mechanism for passing a bootstrap context to a resource adapter instance.
3.endpoint模块
AbstractMessageEndpointFactory:实现了jca 1.5、1.6、1.7版本的javax.resource.spi.endpoint.MessageEndpointFactory接口,它提供了事务管理能力。
GenericMessageEndpointFactory实现了抽象方法,对任意类型的消息监听对象(javax.jms.MessageListener)或者javax.resource.cci.MessageListener对象提供了事务管理的能力。
GenericMessageEndpointManager管理类,对上述方法进行管理。
4.support模块
LocalConnectionFactoryBean:创建一个本地JCA连接工厂。
ResourceAdapterFactoryBean :使用BootStrapContext启动一个jca 1.5指定的ResouceAdapter。
5. work模块
结构如下:
WorkManager提供了提交Work(Work继承了Runnable)可执行实例的便利类。
3.3 Transaction Module
Spring Transaction architecture
Architecture of 3.3.1 Transaction management Platformtransactionmanager
As shown in the following:
The core interface of the platformtransactionmanager:spring transaction.
3.3. 2 Transaction Definition Transactiondefinition schema
As shown in the following:
Transactiondefinition: An interface that defines the properties of a spring container transaction.
Includes transaction propagation behavior types and transaction isolation levels:
Transaction propagation Behavior Type
Transaction propagation behavior type |
Description |
PR opagation_required |
If there is currently no transaction, create a new transaction, if one is already in the transaction, join the transaction. This is the most common choice. |
Propagation_supports |
supports the current transaction and is executed in a non-transactional manner if no transactions are currently in use. |
propagation_mandatory |
Use the current transaction and throw an exception if there is no current transaction. |
propagation_requires_new |
Create a new transaction, suspend the current transaction if a transaction is currently present. |
propagation_not_supported |
Perform the operation in a non-transactional manner, if a transaction is currently present, Suspends the current transaction. |
Propagation_never |
" is executed in a non-transactional manner and throws an exception if a transaction is currently present. |
propagation_nested |
Executes within a nested transaction if a transaction is currently present. If there is currently no transaction, perform a similar operation as propagation_required. |
When using propagation_nested, the underlying data source must be based on JDBC 3.0, and the implementation needs to support the savepoint transaction mechanism.
Isolation level:
To avoid several scenarios where 4 transaction isolation levels are defined in the standard SQL specification, different isolation levels are different for transaction processing
1. Unauthorized read (READ UNCOMMITTED): Also known as uncommitted read. Prevent updates from being lost (this does not correspond to a one-level lock), and if one transaction has already started writing the data, the other data does not allow simultaneous writes but allows other transactions to read the row data. This isolation level can be achieved through an "exclusive write lock". The lowest level of transaction isolation, which guarantees that no physical corruption is read. Contrary to the read COMMITTED isolation level, it allows the reading of data that has been modified by other users but not yet committed.
2. Authorized read (read Committed): Also known as read-committed. Above 1 prevents dirty reads (this does not correspond to level two locks). This can be achieved through "instantaneous shared read lock" and "Exclusive write lock", where the transaction that reads the data allows other transactions to continue to access the row's data, but the uncommitted write transaction will prevent other transactions from accessing the row. The default level for SQL Server. Under this isolation level, the SELECT command does not return data that has not yet been committed (Committed), and it cannot return dirty data.
3. Repeatable READ (Repeatable Read): 2 prevents non-repeatable reads (this does not correspond to level three locks). However, phantom data may sometimes occur, which can be achieved through "shared read lock" and "Exclusive write lock", which will prohibit write transactions (but allow read transactions), and write transactions prohibit any other transactions. At this isolation level, data that is read with the Select command is not changed during the execution of the entire command. This option affects the performance of the system, and it is best not to use this isolation level for unnecessary situations.
Level three blocking protocol does not prevent Phantom reading, the modified can no longer be read, but the number of new (deleted) records may be counted.
4. Serial (Serializable): Also known as Serializable (this does not correspond to a two-segment lock). Provides strict transaction isolation, which requires transactional serialization execution, and transactions can be executed one after the other, but not concurrently. If transaction serialization is not possible only through row-level locks, other mechanisms must be ensured that the newly inserted data is not accessed by the just executing query operation transaction. The highest level of transaction isolation, which is completely isolated between transactions. If transactions run at the serializable read isolation level, then any concurrent overlapping transactions can be guaranteed to be serial.
Lu lost update Dr Dirty read NRR non-repeatable read SLU Two class lost update PR Phantom read
To resolve issues related to the request for the same data by multiple threads, the transactions are separated from each other by locks. Most mainstream databases support different types of locks; therefore, the JDBC API supports different types of transactions, which are assigned or determined by the Connection object. In order to strike a balance between performance and consistency, there are several levels above. The higher the level of transaction protection, the greater the performance penalty. Assuming that your database and the JDBC driver support this feature, given a Connection object, you can explicitly set the desired transaction level: Conn.settransactionlevel (transaction_serializable); The level of the current transaction can be determined by the following methods:
int level = Conn.gettransactionisolation ();
Savepointmanager: A programmatic API interface for managing transaction savepoint.
JDBC defines the SavePoint interface, which provides a finer-grained transaction control mechanism. when a savepoint is set, you can rollback to the state at that SavePoint instead of rollback the entire transaction. the Setsavepoint and Releasesavepoint methods of the connection interface allow you to set and release savepoint points.
Transactionstatus: Transaction state representation.
3.3. 3 Spring Transaction Implementation mechanism
1 High-rise
The better Way is: 1. Template method based on persistent layer API; 2. Use a local ORM api;3 with transaction factory beans to manage the local resource factory using a proxy.
2 Bottom
DataSourceUtils
(used as a JDBC transaction), (as a JPA transaction), (as a EntityManagerFactoryUtils
SessionFactoryUtils
hibernate transaction), PersistenceManagerFactoryUtils
(as a JDO transaction), etc.
For example, when using JDBC, you can get the connection without using the getconnection () method of the DataSource, but instead use the following methods:
Connection conn = datasourceutils.getconnection (DataSource);
3 Lowest Layer
TransactionAwareDataSourceProxy是事务的最底层,它代理了DataSource,并增加了spring管理事务功能。
Resources:
1.http://www.educity.cn/rk/457230.html
2. http://uule.iteye.com/blog/1445678
3. http://zhxing.iteye.com/blog/368110
Spring transaction Source Analysis-Transaction architecture