Spring programming transactions and spring Programming

Source: Internet
Author: User

Spring programming transactions and spring Programming

Take a look at the configuration file (simple configuration)
<Pre name = "code" class = "html"> <! -- Configure the data source --> <bean id = "dataSource" class = "com. mchange. v2.c3p0. comboPooledDataSource "destroy-method =" close "> <property name =" driverClass "> <value >$ {jdbc. driverClassName} </value> </property> <property name = "jdbcUrl"> <value >$ {jdbc. url} </value> </property> <property name = "user"> <value >$ {jdbc. username} </value> </property> <property name = "password"> <value >$ {jdbc. password} </value> </property> <span style = "white-space: pre"> </span> </bean>
 
 

Spring Transaction Manager

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">       <property name="dataSource"><ref bean="dataSource"/>   </property>    </bean>


There is no use of spring to inject transactionManager here. Of course, you can use spring to help you inject transactionManager, And you can enable the transaction after obtaining it. Here, you use a programmatic transaction because I want to use Connection.

/*** Randomly obtained connections. When used up, release */private Connection queryConnection;/*** transaction Connection, which is retained during a transaction and released after the transaction is committed */private Connection transactionConn; private DataSourceTransactionManager transactionManager = (DataSourceTransactionManager) ContextLoaderListener. getCurrentWebApplicationContext (). getBean ("transactionManager");/*** transaction status */private TransactionStatus transactionStatus;

Start and submit transactions

Public void closeQueryConn () {try {if (this. queryConnection! = Null &&! This. queryConnection. isClosed ()&&! This. queryConnection. equals (this. transactionConn) {this. queryConnection. close () ;}} catch (SQLException e) {e. printStackTrace ();} finally {this. queryConnection = null;}/*** release the session of the current thread */public void releaseSession () {if (SessionFactory. getThreadSession () = this) {SessionFactory. releaseSession ();} else {this. closeConn () ;}}/*** start transaction * @ throws SQLException */public void beginTransaction () throws SQ LException {if (this. transactionStatus = null | this. transactionStatus. isCompleted () {// if there is a transaction connection, close the normal query connection and use the transaction connection as the query connection this. closeQueryConn (); DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition (); // spring transaction Propagation Behavior PROPAGATION_REQUIRED: if a transaction exists, it is added to the transaction. If no transaction exists, creates a new transaction. TransactionDefinition. setPropagationBehavior (DefaultTransactionDefinition. PROPAGATION_REQUIRED); // transaction isolation level ISOLATION_READ_COMMITTED: indicates that one transaction can only read data committed by another transaction. This level can prevent dirty reads, which is also the recommended value in most cases. TransactionDefinition. setIsolationLevel (DefaultTransactionDefinition. ISOLATION_READ_COMMITTED); // start the transaction this. transactionStatus = this. transactionManager. getTransaction (transactionDefinition); DataSource cancel cel = this. transactionManager. getDataSource (); this. transactionConn = DataSourceUtils. getConnection (cmdcel); this. queryConnection = this. transactionConn ;}/ *** submit the transaction * @ throws SQLException */ Public void commitTransaction () {closeQueryConn (); try {if (this. transactionConn! = Null &&! This. transactionConn. isClosed () {if (! This. transactionConn. getAutoCommit () {try {// conn. commit (); this. transactionManager. commit (transactionStatus);} catch (TransactionException e) {// conn. rollback (); this. transactionManager. rollback (transactionStatus) ;}} this. transactionConn. close () ;}} catch (SQLException e) {e. printStackTrace ();} finally {this. transactionConn = null ;}}

 

For the above Code, here are some instructions:

This. transactionStatus = this. transactionManager. getTransaction (transactionDefinition); after the transaction is enabled, this. transactionConn = ceceutils. getConnection (dataSourcel );

The obtained connection has opened the transaction. this. transactionConn. getAutoCommit () is false.

(If you open a transaction that is not committed, open another transaction:

TransactionStatus1 = this. transactionManager. getTransaction (transactionDefinition );

TransactionStatus2 = this. transactionManager. getTransaction (transactionDefinition );

These two transactionStatus objects are not the same,

TransactionConn1 = performanceutils. getConnection (canccel );

TransactionConn2 = performanceutils. getConnection (canccel );

TransactionConn is the same connection,

TransactionManager. commit (transactionStatus2); will not cause transactionStatus1 to be submitted, but transactionManager. commit (transactionStatus1) will submit transactionStatus2 content, but transactionStatus2 still shows not submitted, that is, commit () is false)

After the transaction is committed, this. transactionManager. commit (transactionStatus); this. transactionConn. getAutoCommit () is true


Transaction isolation level

Isolation level refers to the degree of isolation between several concurrent transactions. The TransactionDefinition interface defines five constants at the isolation level:

  • TransactionDefinition. ISOLATION_DEFAULT: This is the default value, indicating that the default isolation level of the underlying database is used. For most databases, this value is usually TransactionDefinition. ISOLATION_READ_COMMITTED.
  • TransactionDefinition. ISOLATION_READ_UNCOMMITTED: This isolation level indicates that a transaction can read data modified by another transaction but has not yet been committed. This level does not prevent dirty reads and non-repeated reads. Therefore, this isolation level is rarely used.
  • TransactionDefinition. ISOLATION_READ_COMMITTED: This isolation level indicates that one transaction can only read the data committed by another transaction. This level can prevent dirty reads, which is also the recommended value in most cases.
  • TransactionDefinition. ISOLATION_REPEATABLE_READ: This isolation level indicates that a transaction can execute a query multiple times throughout the process, and the records returned each time are the same. Even if the newly added data between multiple queries meets the query requirements, these new records are ignored. This level prevents dirty reads and non-repeated reads.
  • TransactionDefinition. ISOLATION_SERIALIZABLE: all transactions are executed one by one, so that there is no interference between transactions. That is to say, this level can prevent dirty reads, non-repeated reads, and Phantom reads. However, this will seriously affect the program performance. This level is usually not used.
Transaction Propagation Behavior

Transaction propagation means that if a transaction context already exists before the current transaction starts, there are several options to specify the execution behavior of a transaction method. The definition of TransactionDefinition includes the following constants that indicate the Propagation Behavior:

  • TransactionDefinition. PROPAGATION_REQUIRED: this transaction is added if a transaction exists. If no transaction exists, a new transaction is created.
  • TransactionDefinition. PROPAGATION_REQUIRES_NEW: Creates a new transaction. If a transaction exists, the current transaction is suspended.
  • TransactionDefinition. PROPAGATION_SUPPORTS: if a transaction exists, it is added to the transaction. If no transaction exists, it continues to run as a non-transaction.
  • TransactionDefinition. PROPAGATION_NOT_SUPPORTED: runs in non-transaction mode. If a transaction exists, the current transaction is suspended.
  • TransactionDefinition. PROPAGATION_NEVER: runs in non-transaction mode. If a transaction exists, an exception is thrown.
  • TransactionDefinition. PROPAGATION_MANDATORY: this transaction is added if a transaction exists. If no transaction exists, an exception is thrown.
  • TransactionDefinition. PROPAGATION_NESTED: if a transaction exists, create a transaction to run as a nested transaction of the current transaction. If no transaction exists, the value is equivalent to TransactionDefinition. PROPAGATION_REQUIRED.

It should be pointed out that the previous six transaction propagation behaviors are introduced by Spring from EJB and they share the same concept. PROPAGATION_NESTED is unique to Spring. Transactions started with PROPAGATION_NESTED are embedded in external transactions (if an external transaction exists). At this time, the embedded transaction is not an independent transaction and depends on the existence of external transactions, internal transactions can only be committed through external transactions. nested subtransactions cannot be committed independently. If you are familiar with the concept of SavePoint in JDBC, nested transactions are easy to understand. In fact, nested sub-transactions are an application that saves points, A transaction can contain multiple storage points and each nested sub-transaction. In addition, the rollback of external transactions will also lead to the rollback of nested sub-transactions.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.