Spring transaction isolation level and propagation mechanism, Spring+mybatis+atomikos implementation of distributed transaction management

Source: Internet
Author: User
Tags websphere application server

This article is reproduced in "http://blog.csdn.net/liaohaojian/article/details/68488150"1. Definition of a transaction: A transaction is a collection of multiple operating units, where multiple unit operations are integral, either unsuccessful or successful. It must follow four principles (ACID).
    1. atomicity (atomicity): That is, the transaction is the smallest unit of work, and the operations within the transaction either do it all or do nothing;
    2. Consistency (consistency): The data in the database is in the correct state before the transaction executes, and the data of the database should be in the correct state after the transaction execution is complete, that is, the data integrity constraint is not destroyed; For example, bank transfer, a transfer to B, must guarantee that A's money will be transferred to B , it's not going to happen. A's money is gone but B is confiscated, otherwise the data in the database is in an inconsistent (incorrect) state.
    3. Isolation (Isolation): Concurrent transaction execution does not affect each other, operations within one transaction do not have an impact on other transactions, which requires a transaction isolation level to specify isolation;
    4. persistence (Durability): Once a transaction succeeds, its data changes to the database must be permanent and will not be inconsistent or lost due to, for example, a system failure or power outage.
2. Types of Transactions
    1. The database is divided into local transactions and global transactions
      • Local transaction: Normal transaction, independent of a database, can guarantee the operation of acid on the database.
      • Distributed transactions: Transactions that involve two or more database sources, that is, transactions that span multiple homogeneous or heterogeneous databases (consisting of local transactions per database), are designed to ensure that all operations of these local transactions are acid-capable, allowing transactions to span multiple databases;
    2. Java transaction types are divided into JDBC transactions and JTA transactions
      • JDBC Transaction: This is the local transaction in the database transaction mentioned above, managed by connection object control.
      • JTA transaction: JTA refers to the Java Transaction API (Java Transaction API), is the Java EE Database transaction specification, JTA only provides the transaction management interface , by the application server vendor (such as WebSphere application Server) provides implementations where JTA transactions are more powerful than JDBC and support distributed Transactions .
    3. According to whether it is programmed into declarative transactions and programmatic transactions, refer to http://blog.csdn.net/liaohaojian/article/details/70139151
      • Declarative transactions: Implemented through XML configuration or annotations.
      • Programmatic transactions: The programming code is self-fulfilling when required by the business logic and is less granular.
3.Spring Transaction ISOLATION level: Spring has five isolation levels, which are defined in the Transactiondefinition interface. See source, its default isolation_default (the bottom level of the database), the other four isolation levels consistent with the database isolation level.
  1. Isolation_default: With the default isolation level of the underlying database, the database administrator sets what is what
  2. isolation_read_uncommitted (Read UNCOMMITTED): The lowest isolation level, the transaction is not committed before it can be read by other transactions (Phantom read, dirty read, non-repeatable read)
  3. isolation_read_committed (Read-committed): A transaction is committed before it can be read to by another transaction (the isolation level prevents other transactions from reading data to uncommitted transactions, so it can cause phantom reads, non-repeatable reads), SQL Server default level
  4. Isolation_repeatable_read (Repeatable Read): Repeatable read, guaranteed multiple reads consistent, prohibit reading to other transactions uncommitted data (the isolation is basically to prevent dirty read, non-repeatable read (emphasis on modification), But there will be phantom reads (emphasis on adding and deleting)) (MySQL default level, change can be set TRANSACTION isolation level )
  5. isolation_serializable (serialization): The most expensive and reliable isolation level (this isolation level prevents dirty reads, non-repeatable reads, Phantom reads)
    1. Missing update: Two transactions update a row of data at the same time, the last transaction update overwrites the update of the first transaction, resulting in the loss of data for the first transaction update, which is caused by no lock-in;
    2. Phantom reads: In the same transaction, reads the contents of another uncommitted transaction on multiple reads, resulting in inconsistencies with the content of the first read (typically, the number of rows becomes more or less).
    3. Dirty reads: One transaction reads to another without mentioning the contents of the transaction, which is dirty read.
    4. Non-repeatable reads: In the same transaction, multiple reads are inconsistent (the average number of rows is constant and the content is changed).

The difference between phantom reading and non-repeatable reading: The focus of Phantom reading is to insert and delete , that is, the second query will find less or more than the first query data, so as to give the illusion of the same, and non-repeatable reading focus on the changes , That is, the second query will find that the results of the query are inconsistent with the results of the first query, that is, the first result is not reproducible.

The higher the database isolation level, the higher the execution cost, and the worse the concurrent execution, so in the actual project development use to consider comprehensively, in order to consider concurrency performance generally use the read-committed isolation level, it can avoid loss of updates and dirty read, although non-repeatable read and Phantom read can not be avoided, However, you can use pessimistic or optimistic locks to solve these problems where possible.

Pessimistic lock and optimistic lock can refer to: http://blog.csdn.net/liaohaojian/article/details/62416972

4. Propagation behavior: There are seven major propagation behaviors, also defined in the Transactiondefinition interface.
    1. propagation_required: Supports the current transaction, such as a new one if there is no transaction currently.
    2. propagation_supports: Support the current transaction, such as no transaction currently, is non-transactional execution (the source hints that there is a point of attention, not quite clear, left behind).
    3. propagation_mandatory: Supports the current transaction, such as no transaction at the moment, throws an exception (forcing must be performed in an already existing transaction, the business method cannot initiate its own transaction alone).
    4. propagation_requires_new: Always create a new transaction, such as the current transaction, suspends the original transaction.
    5. propagation_not_supported: The current transaction is not supported and is always performed in a non-transactional manner, such as the current transaction exists and the transaction is suspended.
    6. propagation_never: The current transaction is not supported and an exception is thrown if the current transaction exists.
    7. propagation_nested: Executes in a nested transaction if the current transaction exists, and performs an operation similar to propagation_required if there is no current transaction (Note: JDBC is only applicable when applied to JDBC More than 3.0 drives).
5.Spring Transaction Support
The 1.spring provides a number of built-in transaction managers that support different data sources. There are three main categories of common
    • Datasourcetransactionmanager Org.springframework.jdbc.datasource: The data source transaction management class, which provides transaction management for a single javax.sql.DataSource data source, as long as it is used for Jdbc,mybatis framework transaction management.
    • Hibernatetransactionmanager : Org.springframework.orm.hibernate3 package, data source transaction management class, provides transaction management support for single org.hibernate.SessionFactory transaction, for integration of Hibernate framework; NOTE: The transaction manager only supports the hibernate3+ version, and the spring3.0+ version only supports hibernate 3.2+ version;
    • Jtatransactionmanager: In the ORG.SPRINGFRAMEWORK.TRANSACTION.JTA package, providing support for distributed transaction management and delegating transaction management to Java EE application Server, or customize a local JTA transaction manager, nested into the application.

The built-in transaction manager inherits the abstract class Abstractplatformtransactionmanager, and Abstractplatformtransactionmanager inherited the interface Platformtransactionmanager

The core of the Spring Framework support transaction management is transaction manager abstraction, which can support the transaction management of multi-clock data access framework by implementing the policy interface Platformtransactionmanager for different data access frameworks.

The Platformtransactionmanager interface is defined as follows

Public interface Platformtransactionmanager {         transactionstatus gettransaction (transactiondefinition definition Throws transactionexception;//returns a transaction that has already been activated or creates a new transaction (determined by the transaction property defined by the Transactiondefinition parameter). The returned Transactionstatus object represents the state of the current transaction, where the method throws a TransactionException (unchecked exception) to indicate that the transaction failed for some reason.         void commit (Transactionstatus status) throws transactionexception;//is used to commit the transaction represented by the Transactionstatus parameter.         the void rollback (Transactionstatus status) throws transactionexception;//is used to rollback the transaction represented by the Transactionstatus parameter. }

The Transactiondefinition interface is defined as follows:

Public interface Transactiondefinition {         int getpropagationbehavior ();  Returns the transaction propagation behavior defined by       int getisolationlevel ();//return transaction ISOLATION Level       int gettimeout ();  Returns the defined transaction timeout time       , Boolean isreadonly ();  Returns whether the defined transaction is a read-only       String getName ();  
The Transactionstatus interface is defined as follows:
Public interface Transactionstatus extends Savepointmanager {         boolean isnewtransaction ();  Returns whether the current transaction is a new transaction,       Boolean hassavepoint ();  Returns whether the current transaction has a save point of       void Setrollbackonly ();  Sets the transaction rollback       Boolean isrollbackonly ();  Sets whether the current transaction should roll back       void Flush ();  Used to refresh the modifications in the underlying session to the database, typically for refreshing sessions such as HIBERNATE/JPA, which may have no effect on transactions such as JDBC type;       boolean iscompleted ();  Returns whether the transaction is complete}  

2.Spring Distributed Transaction Configuration

    • A Jndi data source referencing an application server (such as Tomcat) that indirectly implements JTA transaction management and relies on the application server
    • Direct Integration Jotm (official website: http://jotm.objectweb.org/), Atomikos (official website: https://www.atomikos.com/) provides JTA transaction management (no application server support, often used for unit testing)
    • Using the application server-specific transaction manager, use the advanced features of the JTA transaction (Weblogic,websphere)

1). Refer to the Jndi data source of the application server (such as Tomcat), implement JTA Transaction management indirectly, configure the following

<beans xmlns= "Http://www.springframework.org/schema/beans"    xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "    xmlns:jee=" Http://www.springframework.org/schema/jee "    xsi:schemalocation=       " Http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsd       Http://www.springframework.org/schema/jee       http://www.springframework.org/schema/ Jee/spring-jee-3.0.xsd "> <!--jndi data Source--  <jee:jndi-lookup id=" DataSource "jndi-name=" jdbc/test "/ >    <!--JTA transaction Manager-  -  <bean id= "Txmanager" class= " Org.springframework.transaction.jta.JtaTransactionManager ">  <!-- TRANSACTIONMANAGERNAME Specifies the Jndi name of the JTA transaction manager to delegate transaction management to the transaction manager--    <property name= " Transactionmanagername "value=" Java:comp/transactionmanager "/>  </bean></beans>

2) Implement distributed transaction Management using Atomikos, configured as follows:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:p= "http://www.springframework.org/schema/p" xmlns:aop= " Http://www.springframework.org/schema/aop "xmlns:tx=" Http://www.springframework.org/schema/tx "xmlns:context=" Http://www.springframework.org/schema/context "xmlns:task=" Http://www.springframework.org/schema/task "xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.0.xsdhttp://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/ spring-tx-3.0.xsdhttp://www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/ spring-task-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/ Spring-aop-3.0.xsd "> <context:cOmponent-scan base-package= "Com.suicai.*.service.impl"/><context:component-scan base-package= " Com.suicai.util "/> <!--the configuration file loaded by this method is used only in XML, but the tool classes are annotated--><bean class=" Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer "><property name=" Location "value=" Classpath:conn.properties "/></bean><!--only support annotations do not support the use of the properties file in the XML configuration can use the Spel expression in the class to load the corresponding value- <bean id= "temp" class= "Org.springframework.beans.factory.config.PropertiesFactoryBean" ><property name= " Locations "><array><value>classpath:public.properties</value></array></property ></bean><bean id= "Abstractxadatasource" class= "Com.atomikos.jdbc.AtomikosDataSourceBean" init-method= "Init" destroy-method= "Close" abstract= "true" > <property name= "borrowconnectiontimeout" value= "/> &l" t;! --Get the connection failed to regain the wait maximum time, if there is an available connection, will return-<property name= "reaptimeout" value= "/> <!--maximum fetch data time, if not set this value , AtomiKos uses the default of 5 minutes, then when processing a large amount of data read, once more than 5 minutes, will be thrown like Resultset is close error .--> <property name= "Maintenanceinte Rval "value="/> <!--Connection Collection time-<property name= "LoginTimeout" value= "/>" <!--java data Library connection pool, max wait to get datasouce time--<property name= "LogWriter" value= "/> <property name=" "></pr operty> <property name= "Minpoolsize" value= "1"/> <!--the minimum number of connections kept in the connection pool--<property name= "Maxpoolsize" value= "3"/> <!--the maximum number of connections left in the connection pool-<property name= "MaxIdleTime" value= "Up"/> < !--maximum idle time, unused in 60 seconds, the connection is discarded. If 0, it will never be discarded. default:0-</bean> <!--configuring 2 data sources mysql--<bean id= "Ds_suicai" parent= "Abstractxadatasou Rce "> <!--uniqueresourcename represents a unique resource name, if multiple data sources are not repeatable;--<property Name=" Uniqueresourcename "value=" sui Caifortest "/> <!--Xadatasourceclassname is a specific distributed data source vendor implementation;--<property Name=" XadatasourceclaSsname "value=" Com.mysql.jdbc.jdbc2.optional.MysqlXADataSource "/> <!--xaproperties properties Specify specific vendor database properties--< Property name= "Xaproperties" > <props> <prop key= "URL" &GT;${DB.JDBCURLONE}&LT;/PROP&G                T            <prop key= "User" >${user}</prop> <prop key= "password" >${password}</prop> </props> </property> </bean> <bean id= "Ds_kaizhi" parent= "Abstractxadatasource" > < !--Uniqueresourcename represents a unique resource name, if multiple data sources are not repeatable;--><property name= "Uniqueresourcename" value= " Puildingpurchasefortest "/><!--Xadatasourceclassname is a specific distributed data source vendor implementation;--><property Name=" Xadatasourceclassname "value=" Com.mysql.jdbc.jdbc2.optional.MysqlXADataSource "/><!-- The Xaproperties property specifies the specific vendor database properties--><property name= "Xaproperties" > <props> <prop key= "URL" >${db.jdbcUrlTwo}</prop> <prop key= "user" >${user}</prop> <prop key= "password" >${password}</prop> </props> </proper Ty> </bean> <!--dynamic configuration data Source-<bean id= "DataSource2" class= "Com.suicai.common.datasource.Dyna Micdatasource "> <property name=" targetdatasources "> <map key-type =" Java.lang.String "                  ; <entry value-ref = "Ds_suicai" key= "Ds_suicai" ></entry > <entry value-ref = "Ds_kaizhi" key= "Ds_kaizhi" ></entry > </map > </property> <property name = "Defaultta Rgetdatasource "ref=" Ds_suicai "></property> </bean> <bean id =" Sqlsessionfactorybeana "cl ass= "Org.mybatis.spring.SqlSessionFactoryBean" > <!--Specify data source-<property name = "DataSource" R ef= "Ds_suicai"/> <!--Specify the configuration file for MyBatis--<property name = "Configlocation" value= "classpath:m YbatiS.cfg.xml "/> </bean><bean id =" SQLSESSIONFACTORYBEANB "class=" Org.mybatis.spring.SqlSessionFactoryBean > <!--Specify data source-<property name = "DataSource" ref= "Ds_kaizhi"/> <!--specify Mybati s configuration file--<property name = "Configlocation" value= "Classpath:mybatis.cfg.xml"/> </bean><!--Cu Stomsqlsessiontemplate inherit Sqlsessiontemplate override getsqlsessionfactory method, please download view--<bean id= "sqlsessiontemplate "Class=" Com.suicai.util.CustomSqlSessionTemplate "scope=" prototype "> <constructor-arg ref=" sqlsessionfactor  Ybeana "/> <property name=" Targetsqlsessionfactorys "> <map> <entry Value-ref = "Sqlsessionfactorybeana" key= "Ds_suicai1" ></entry > <entry value-ref = "SqlSession      Factorybeanb "key=" Ds_kaizhi1 "></entry > </map> </property> </bean> <!--configuring Atomikos transaction manager--><beanId= "Atomikostransactionmanager" class = "Com.atomikos.icatch.jta.UserTransactionManager" init-method= "Init" Destroy-method = "Close" > <property name= "Forceshutdown" value= "true"/> </bean> <bean id= "Atomikosusertransaction" class= "COM.ATOMIKOS.ICATCH.JTA.USERTRANSACTIONIMP" ></bean><!-- Configure Spring transaction manager--><bean id= "TransactionManager" class= "            Org.springframework.transaction.jta.JtaTransactionManager "> <property name=" TransactionManager ">            <ref bean= "Atomikostransactionmanager"/> </property> <property name= "UserTransaction" > <ref bean= "Atomikosusertransaction"/> </property> <!--must be set, or the program will be abnormal Jtatransactionman Ager does not support custom isolation levels by default--<property name= "allowcustomisolationlevels" value= "t Rue "/> </bean><tx:advice id=" Advice "transaction-manager=" TransactionManager "><tx:attributes    ><!--REQUIRED: You must have a transaction if you do not create a--><tx:method name= "save*" propagation= "REQUIRED" in the context/><tx:method Name= "creat*" propagation= "REQUIRED"/><tx:method name= "add*" propagation= "REQUIRED"/><tx:method name= " update* "propagation=" REQUIRED "/><tx:method name=" delete* "propagation=" REQUIRED "/><!--support, if there is, there is no --><tx:method name= "*" propagation= "SUPPORTS"/></tx:attributes></tx:advice><aop:config > <aop:pointcut expression= "Execution (* com.suicai.*.service.impl.*.* (..))" id= "Pointcut"/> <!--bar Tx and AO P's configuration association is the complete declaration transaction configuration--<aop:advisor advice-ref= "advice" pointcut-ref= "Pointcut"/></aop:config><! --Using the packet scanning mechanism, automatically registers all the DAO inside the specified package--><bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" ><!-- Note Inject Sqlsessiontemplate--<property name= "Sqlsessiontemplatebeanname" value= "Sqlsessiontemplate"/&GT;&LT;PR Operty name= "Basepackage" value= "Com.suicai.*.dao"/></bean><bEan id= "Viewresolver" class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" ><property Name= "Viewclass" ><value>org.springframework.web.servlet.view.internalresourceview</value></ property><!--JSP storage directory--><property name= "prefix" ><value>/</value></property> <!--jsp file suffix--><property name= "suffix" ><value>.jsp</value></property></bean ><!--Verification Code--><bean id= "Captchaproducer" class= "Com.google.code.kaptcha.impl.DefaultKaptcha" > <p Roperty name= "config" > <bean class= "com.google.code.kaptcha.util.Config" > <const ructor-arg> <props> <prop key= "Kaptcha.border" >no</prop&gt                          ; <prop key= "Kaptcha.border.color" >105,179,90</prop> <prop key= "Kaptcha.textproducer                . Font.Color ">red</prop>          <prop key= "Kaptcha.image.width" >200</prop> <prop key= "Kaptcha.textproduc                          Er.font.size ">60</prop> <prop key=" Kaptcha.image.height ">80</prop> <prop key= "Kaptcha.session.key" >code</prop> <prop key= "Kaptcha.tex Tproducer.char.length ">4</prop> <prop key=" Kaptcha.textproducer.font.names "> Arial, Italic,           Microsoft Ya-Black </prop> </props> </constructor-arg> </bean> </property> </bean> <bean id= "Messagesource" class= "ORG.SPRINGFRAMEWORK.CONTEXT.SUPPORT.R Eloadableresourcebundlemessagesource "> <property name=" basename "value=" Classpath:messages "/> & Lt;property name= "fileencodings" value= "Utf-8"/> <property name= "cacheseconds" value= "+"/> </bean&  Gt;</beans>

Atomikos required package and related configuration file download path: http://download.csdn.net/detail/liaohaojian/9810401, where the file Jta.properties file is placed in the Classpath root directory.

Spring transaction isolation level and propagation mechanism, Spring+mybatis+atomikos implementation of distributed transaction management

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.