Mybatis Transaction Management Mechanism

Source: Internet
Author: User

Mybatis is a Java database framework. It is very important to manage database transactions. This article describes the implementation mechanism of mybatis transaction management. First, we will introduce the interface design and different implementations of mybatis transaction.JdbctransactionAndManagedtransactionNext, start with the xml configuration file of mybatis to explain the creation and maintenance of mybatis transaction factory, and then elaborate on the creation and use of mybatis transactions.JdbctransactionAndManagedtransactionImplementation and different features of the two.

The organizational structure of this article is as follows:


I. Overview

For database transactions, there should be the following aspects: Create, commit, rollback, and close ). Correspondingly, mybatis abstracts transactions into transaction interfaces, which are defined as follows:

The transaction management of mybatis is divided into two forms:

I. Use the JDBC Transaction Management Mechanism: Uses the java. SQL. connection object to commit transactions (COMMIT (), Roll Back (), close (), and so on.

Ii. Use the managed Transaction Management Mechanism:This mechanism, mybatis itself, does not implement transaction management, but enables program containers such as (JBoss, WebLogic) to manage transactions.

The two classes are shown as follows:

Ii. Configure, create, and use transactions
1. Transaction Configuration

When using mybatis, the following information is defined in the mybatisxml configuration file:

<Environment> A node defines the information for connecting to a database. Its subnodes <Transactionmanager> Type determines what type of transaction management mechanism we use.

2. Create a transaction Factory

The mybatis transaction is created by the transactionfactory transaction factory. If we configure the <transactionmanager> type to "JDBC", when mybatis initializes the parsing <environment> node, A jdbctransactionfactory factory is created based on type = "JDBC". The source code is as follows:

/*** Parse the <transactionmanager> node and create the corresponding transactionfactory * @ Param context * @ return * @ throws exception */private transactionfactory transactionmanagerelement (xnode context) throws exception {If (context! = NULL) {string type = context. getstringattribute ("type"); properties props = context. getchildrenasproperties ();/* during configuration initialization, the following statement is used to provide the factory class typealiasregistry for JDBC and managed. registeralias ("JDBC", jdbctransactionfactory. class); typealiasregistry. registeralias ("managed", managedtransactionfactory. class); The following resolveclass (type ). newinstance () will create the corresponding factory instance */transactionfactory factory = (transactionfactory) resolveclass (type ). newinstance (); factory. setproperties (props); Return factory;} Throw new builderexception ("Environment Declaration requires a transactionfactory. ");}

As shown in the code above, if type = "JDBC", mybatis will create a jdbctransactionfactory. class instance; If type = "managed", mybatis will create a mangedtransactionfactory. class instance.

Mybatis pair <Transactionmanager> Node parsing generates a transactionfactory instance.Datasource> The datasouce instance is generated during parsing. (For details about datasource parsing and principles, refer to another blog: "understanding the principle of mybatis" mybatis data source and connection pool.
), As <Environment> Node. An environment object is created based on the transactionfactory and datasource instances. The Code is as follows:

Private void environmentselement (xnode context) throws exception {If (context! = NULL) {If (Environment = NULL) {environment = context. getstringattribute ("default");} For (xnode child: context. getchildren () {string id = child. getstringattribute ("ID"); // If (isspecifiedenvironment (ID) resolved in the same environment as the default environment {// 1. parse the <transactionmanager> node and decide what type of transactionfactory txfactory = transactionmanagerelement (child. evalnode ("transactionmanager"); // 2. create datasource performancefactory dsfactory = performanceelement (child. evalnode ("datasource"); datasource = dsfactory. getdatasource (); // 3. the built-in constructor builder of environment is used to pass the ID transaction factory transactionfactory and the data source datasource environment. builder environmentbuilder = new environment. builder (ID ). transactionfactory (txfactory ). datasource (datasource); configuration. setenvironment (environmentbuilder. build ());}}}}

EnvironmentIndicates a database connection. The generated environment object will be set in the configuration instance for future use.

The above has been talking about the transaction created by the transaction factory transactionfactory. Now let's take a look at the definition of transactionfactory in mybatis.

3. Transaction factory transactionfactory

The transaction factory transaction defines two methods for creating transaction: one is to create transaction through the specified connection object, and the other is to create transaction through the data source datasource. In contrast to the JDBC and managed transactions, transactionfactory has two implementation subclasses:

4. Create transaction

It is easy to obtain the transaction object instance through the transaction factory transactionfactory. Take jdbctransaction as an example to see how jdbctransactionfactory generates jdbctransaction. The Code is as follows:

Public class jdbctransactionfactory implements transactionfactory {public void setproperties (properties props) {}/*** create transaction * @ Param conn existing database connection * @ return */Public transaction newtransaction (connection conn) based on the given database connection) {return New jdbctransaction (conn );} /*** create a transacion Based on datasource, isolation level, and whether to automatically submit the task ** @ Param DS * @ Param level desired isolation level * @ Param autocommit desired autocommit * @ return */Public transaction newtransaction (datasource ds, transactionisolationlevel level, Boolean autocommit) {return New jdbctransaction (DS, level, autocommit );}}

As mentioned above, jdbctransactionfactory creates a JDBC-type transaction, that is, jdbctransaction. Similarly, managedtransactionfactory also creates managedtransaction. Next we will go deep into jdbctranaction and managedtransaction to see how they implement transaction management.

5. jdbctransaction

Jdbctransaction directly uses the JDBC commit and rollback transaction management mechanism. It depends on the connection obtained from datasource to manage the scope of the transaction. Obtaining the connection object is delayed until the getconnection () method is called. If autocommit is set to on, it ignores commit and rollback.

Specifically, jdbctransaction is a Java. SQL. the commit and rollback functions on connection, jdbctransaction is equivalent to Java. SQL. the connection transaction is encapsulated once (wrapper), and the transaction management of transaction is implemented through Java. SQL. connection implementation. The Code Implementation of jdbctransaction is as follows:

/*** @ See jdbctransactionfactory * // *** @ author Clinton begin */public class jdbctransaction implements transaction {Private Static final log = logfactory. getlog (jdbctransaction. class); // database connection protected connection; // data source protected datasource; // isolation level protected transactionisolationlevel; // whether protected Boolean autocommmit is automatically submitted; public jdbctransaction (datasource ds, Transactionisolationlevel desiredlevel, Boolean desiredautocommit) {datasource = Ds; Level = desiredlevel; autocommmit = desiredautocommit;} public jdbctransaction (connection) {This. connection = connection;} public connection getconnection () throws sqlexception {If (connection = NULL) {openconnection ();} return connection;}/*** commit () use the connection commit () * @ throws sqle Xception */Public void commit () throws sqlexception {If (connection! = NULL &&! Connection. getautocommit () {If (log. isdebugenabled () {log. debug ("committing JDBC connection [" + connection + "]");} connection. commit () ;}/ *** rollback () uses the rollback () * @ throws sqlexception */Public void rollback () throws sqlexception {If (connection! = NULL &&! Connection. getautocommit () {If (log. isdebugenabled () {log. debug ("rolling back JDBC connection [" + connection + "]");} connection. rollback () ;}}/*** close () function use close () * @ throws sqlexception */Public void close () throws sqlexception {If (connection! = NULL) {resetautocommit (); If (log. isdebugenabled () {log. debug ("Closing JDBC connection [" + connection + "]");} connection. close () ;}} protected void setdesiredautocommit (Boolean desiredautocommit) {try {If (connection. getautocommit ()! = Desiredautocommit) {If (log. isdebugenabled () {log. debug ("setting autocommit to" + desiredautocommit + "on JDBC connection [" + connection + "]");} connection. setautocommit (desiredautocommit) ;}} catch (sqlexception e) {// only a very poorly implemented driver wowould fail here, // and there's not much we can do about that. throw new transactionexception ("error handling ing autocommit. "+" Y Our driver may not support getautocommit () or setautocommit (). "+" requested setting: "+ desiredautocommit + ". cause: "+ E, E) ;}} protected void resetautocommit () {try {If (! Connection. getautocommit () {// mybatis does not call commit/rollback on a connection if just selects were timed med. // some databases start transactions with select statements // and they mandate a commit/rollback before closing the connection. // a workaround is setting the autocommit to true before closing the connection. // Sybase throws an exception here. if (log. isdebugenabled () {log. debu G ("resetting autocommit to true on JDBC connection [" + connection + "]");} connection. setautocommit (true) ;}} catch (sqlexception e) {log. debug ("error resetting autocommit to true" + "before closing the connection. cause: "+ E) ;}} protected void openconnection () throws sqlexception {If (log. isdebugenabled () {log. debug ("Opening JDBC connection");} connection = datasource. getconnection (); If (level! = NULL) {connection. settransactionisolation (level. getlevel () ;}setdesiredautocommit (autocommmit );}}

6. managedtransaction

Managedtransaction allows the container to manage the entire lifecycle of the transaction, which means that using the commit and rollback functions of managedtransaction will not affect the transaction, and it will not do anything, it transfers the right of transaction management to the container for implementation. You can see the following managed implementation code at a Glance:

/***** Delay the collection of the connection for the entire life cycle of the container management transaction to the call of the getconnection () method * ignore all commit and rollback operations * by default, you can close a connection, you can also configure it to disable a connection * to allow the container to manage the entire transaction lifecycle * @ see managedtransactionfactory * // *** @ author Clinton begin */public class managedtransaction implements transaction {Private Static final log = logfactory. getlog (managedtransaction. class); Private datasource; priv Ate transactionisolationlevel level; private connection; private Boolean closeconnection; Public managedtransaction (connection, Boolean closeconnection) {This. connection = connection; this. closeconnection = closeconnection;} public managedtransaction (datasource ds, transactionisolationlevel, Boolean closeconnection) {This. datasource = Ds; this. level = level; this. clo Seconnection = closeconnection;} public connection getconnection () throws sqlexception {If (this. connection = NULL) {openconnection ();} return this. connection;} public void commit () throws sqlexception {// does nothing} public void rollback () throws sqlexception {// does nothing} public void close () throws sqlexception {If (this. closeconnection & this. connection! = NULL) {If (log. isdebugenabled () {log. debug ("Closing JDBC connection [" + this. connection + "]");} This. connection. close () ;}} protected void openconnection () throws sqlexception {If (log. isdebugenabled () {log. debug ("Opening JDBC connection");} This. connection = This. datasource. getconnection (); If (this. level! = NULL) {This. Connection. settransactionisolation (this. level. getlevel ());}}}

NOTE: If we use mybatis to build a local program, that is, it is not a web program. If we set the type to "managed", any update operation we perform, even if we finally execute the commit operation, the data will not be retained and will not affect the database. Because we configure mybatis as "managed", that is, mybatis does not manage transactions by itself, and we are running local programs without the transaction management function, the update operations on the database are invalid.


The above isMybatis Transaction Management MechanismIf there are any errors or errors, please correct them and make progress together!



Certificate -----------------------------------------------------------------------------------------------------------------------------------------

This article is fromHttp://blog.csdn.net/luanlouis/If you need to reprint it, please indicate the source. Thank you!



Mybatis Transaction Management Mechanism

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.