Spring-programmed transactions

Source: Internet
Author: User

First look at the configuration file (simple configuration)
<pre name= "code" class= "HTML" ><!--configuration 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, of course, you can take spring to help you inject, get to TransactionManager can open the transaction, here use programmatic transaction, because I want to use connection

/** * Randomly acquired connection, release */private Connection queryconnection;/** * Transaction connection, with transaction period retention, release */private Connection after transaction commit ;p rivate Datasourcetransactionmanager TransactionManager = (Datasourcetransactionmanager) Contextloaderlistener.getcurrentwebapplicationcontext (). Getbean ("TransactionManager");/** * Transaction Status */private Transactionstatus Transactionstatus;

Opening transactions and committing 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;}} /** * Releases the current thread's session */public void Releasesession () {if (sessionfactory.getthreadsession () = = this) { Sessionfactory.releasesession ();} Else{this.closeconn ();}} /** * Open transaction * @throws SQLException */public void BeginTransaction () throws sqlexception{if (This.transactionstatus = = null| | This.transactionStatus.isCompleted ()) {//If there is a transactional connection, close the normal query connection and connect the transaction connection as a query This.closequeryconn ();D Efaulttransactiondefinition transactiondefinition = new defaulttransactiondefinition (); Propagation behavior of//spring transactions PROPAGATION_ REQUIRED: If a transaction is currently present, the transaction is joined and a new transaction is created if there is no current transaction.  Transactiondefinition.setpropagationbehavior (defaulttransactiondefinition.propagation_required);//isolation level of the transaction Isolation_read_committed: Indicates that a transaction can only read data that has been committed by another transaction. This level can prevent dirty reads, which is also a push in most casesRecommended value. Transactiondefinition.setisolationlevel (defaulttransactiondefinition.isolation_read_committed);// Open transaction This.transactionstatus = This.transactionManager.getTransaction (transactiondefinition);D Atasource datasourcel = This.transactionManager.getDataSource (); this.transactionconn = Datasourceutils.getconnection (Datasourcel); This.queryconnection = This.transactionconn;}} /** * COMMIT TRANSACTION * @throws SQLException */public void CommitTransaction () {closequeryconn (); try {if (this.transactionconn! = nul L &&!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 opening the transaction This.transactionconn = Datasourceutils.getconnection (Datasourcel);

Gets the connection already open transaction, This.transactionConn.getAutoCommit () is False

(If you open a transaction without committing, and then open a transaction that is:

TransactionStatus1 = This.transactionManager.getTransaction (transactiondefinition);

TransactionStatus2 = This.transactionManager.getTransaction (transactiondefinition);

These two Transactionstatus objects are not of the same object, but

TRANSACTIONCONN1 = Datasourceutils.getconnection (Datasourcel);

TRANSACTIONCONN2 = Datasourceutils.getconnection (Datasourcel);

Transactionconn is the same connection,

Transactionmanager.commit (TRANSACTIONSTATUS2); does not cause transactionStatus1 commit, but Transactionmanager.commit ( TRANSACTIONSTATUS1) will submit TRANSACTIONSTATUS2 content, but TransactionStatus2 still show no commit, i.e. transactionstatus2.iscompleted () to 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. Five constants representing the isolation level are defined in the Transactiondefinition interface:

  • Transactiondefinition.isolation_default: This is the default value that represents the default isolation level for using the underlying database. For most databases, this value is usually transactiondefinition.isolation_read_committed.
  • Transactiondefinition.isolation_read_uncommitted: This isolation level indicates that one transaction can read data that has been modified by another transaction but has not yet been committed. This level does not prevent dirty reads and non-repeatable reads, so this isolation level is rarely used.
  • Transactiondefinition.isolation_read_committed: This isolation level indicates that a transaction can only read data that has been committed by another transaction. This level prevents dirty reads, which is the recommended value in most cases.
  • Transactiondefinition.isolation_repeatable_read: This isolation level indicates that a transaction can repeatedly execute a query multiple times throughout the process, and that the records returned are the same each time. These new records are ignored even if there are new data that satisfies the query between multiple queries. This level protects against dirty reads and non-repeatable reads.
  • Transactiondefinition.isolation_serializable: All transactions are executed one after the other, so that there is absolutely no possibility of interference between transactions, that is, the level prevents dirty reads, non-repeatable reads, and Phantom reads. However, this will severely affect the performance of the program. This level is not normally used.
Transactional propagation behavior

The so-called transaction propagation behavior is that if a transaction context already exists before the current transaction is started, there are several options to specify the execution behavior of a transactional method. The transactiondefinition definition includes the following constants that represent propagation behavior:

  • Transactiondefinition.propagation_required: If a transaction is currently present, the transaction is joined and a new transaction is created if there is no current transaction.
  • Transactiondefinition.propagation_requires_new: Creates a new transaction and suspends the current transaction if a transaction is currently present.
  • Transactiondefinition.propagation_supports: If a transaction is currently present, the transaction is joined, and if no transaction is currently present, it will continue in a non-transactional manner.
  • Transactiondefinition.propagation_not_supported: Runs in a non-transactional manner, suspending the current transaction if a transaction is currently present.
  • Transactiondefinition.propagation_never: Runs in a non-transactional manner and throws an exception if a transaction is currently present.
  • Transactiondefinition.propagation_mandatory: If a transaction is currently present, the transaction is joined and an exception is thrown if there is no current transaction.
  • Transactiondefinition.propagation_nested: If a transaction is currently present, create a transaction to run as a nested transaction for the current transaction, or if there is no current transaction, The value is equivalent to transactiondefinition.propagation_required.

It should be noted here that the previous six transactional propagation behaviors were introduced by Spring from the EJB and shared the same concepts. And propagation_nested is unique to Spring. A propagation_nested-initiated transaction is embedded in an external transaction (if there is an external transaction), at which point the inline transaction is not a separate transaction, it relies on the existence of the external transaction, and only commits the external transaction to cause the internal transaction to be committed. Nested child transactions cannot be submitted separately. If you are familiar with the concept of savepoint (savepoint) in JDBC, then nested transactions are easy to understand, in fact, nested sub-transactions is an application of the savepoint, a transaction can include multiple savepoint, each nested child transaction. Also, a rollback of an external transaction results in a rollback of the nested transaction.



Spring-programmed transactions

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.