IBatis Chapter 5: transaction management, ibatis Chapter 5 transactions

Source: Internet
Author: User

IBatis Chapter 5: transaction management, ibatis Chapter 5 transactions

-------------------------- 1. What is a transaction ------------------------------

What is a transaction?


It should be noted that the concept of transactions is not for a specific database, but for all databases to follow a principle.
Let's take a look at a classic example. There will be two bank accounts for the transfer between them. At this time, transaction control is required. Otherwise, unexpected errors may occur.
The initial balance information is as follows:


1. Suppose A wants to transfer $1000 to B. Normally, it should be shown below:


2. However, the following may be unsatisfactory:

The reason for this is that A user transfers 1000 to B and A is successful, but when B is preparing to deposit the money transferred by A to B's account, an exception occurs at this time, such as a sudden power failure or a program error that causes the money not to be stored in B's account.

Therefore, we can see how important we are to control through transactions. It ensures that our data is in the same state and achieves the following results:


This is mainly the feature of transactions used. Transfers A and deposits B to the same transaction. If an error occurs at one step, the transaction will be rolled back (that is, once B's deposit error occurs, A's transfer will also fail, and A's money will be rolled back), to A correct state before the operation.

-------------------------- 2. Transaction Features ------------------------------
Since we need to use transactions, we first need to figure out the features of transactions. Only by familiarizing ourselves with these features can we better use transactions to manage our applications as needed.

 

1. atomicity: ensure that all the steps in the transaction belong to the same whole, either all succeeded or all failed.
2. Consistency: The index data needs to be consistent.
3. Isolation: because the resources in the database are in a shared state, there may be multiple user operations at the same time, which may cause data disorder. Therefore, we need to control the isolation feature, only one user operation can be performed at a specific time. After the operation is completed, other users can perform the operation again to ensure data accuracy.
4. Persistence: the database provides the data persistence function. Once an operation is successfully submitted, the data is in a persistent and secure State.

-------------------------- 3. Automatic transactions, local transactions, and global transactions ------------------------------
3.1 Automatic transactions:
When we execute an SQL statement, we generally do not need to use the management transactions we display. A single transaction still exists and is an implicit management function provided by the database, it does not need to start or commit transactions as shown in. In this way, transactions are called automatic transaction management.
It should be noted that if we do not display the management of transactions, the database will provide us with an automatic transaction processing mechanism, regardless of what our SQL statements are like.

3.2 local transactions

In fact, local transactions and global transactions are mainly different in the scope of the business. For example, if we make a transfer to the bank, we can use local transaction control because the entire process only involves one application and one Database, there is no pain in other application interactions, and the business scope is relatively small.

3.3 global transactions
A global transaction is a broad business logic that may span multiple application systems and applications. The logic is the same as that of local transaction management, but the scope is wider.

The global transaction is used to control the transfer of Bank A and Bank B in the same transaction. If both Bank A and B are successfully committed, the transaction will be rolled back if one party encounters an exception, the entire process fails to control data consistency.

-------------------------- 4. Custom transactions ------------------------------
Custom transactions can display control transactions. The following is an example of a bank transfer:
1. Define an account entity
/**
* @ Author Administrator
* Account entity class
*/
Public class Account {

Private int id;

Private String account;

Private int money;

Public int getId (){
Return id;
}

Public void setId (int id ){
This. id = id;
}

Public String getAccount (){
Return account;
}

Public void setAccount (String account ){
This. account = account;
}

Public int getMoney (){
Return money;
}

Public void setMoney (int money ){
This. money = money;
}
}

2. Compile the SQL configuration file
<SqlMap>

<! -- Define aliases for classes and simplify code -->
<TypeAlias alias = "account" type = "com. test. bean. Account"/>

<! -- Query -->
<Select id = "account_select" parameterClass = "java. lang. String" resultClass = "account">
Select account, money from account where account = # account #
</Select>

<! -- Update -->
<Update id = "account_update" parameterClass = "account">
Update account set money = # money # where account = # account #
</Update>

</SqlMap>

3. Test transaction control
Package com. test. dbutil;

Import java. SQL. SQLException;

Import com. ibatis. sqlmap. client. SqlMapClient;
Import com. test. bean. Account;

Public class TestAccount {

/**
* Test Transaction Control Transfer
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub

TestAccount t = new TestAccount ();
Try {
T. exchange1 ("A", "C", 500 );
} Catch (SQLException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}

/**
* Implement the transfer function [transaction control]
* @ Param aname
* @ Param bname
* @ Param money
* @ Throws SQLException
*/
Private void exchange (String aname, String bname, int money) throws SQLException {

SqlMapClient sqlMapClient = BaseDAO. getInstance ();

Try {
// 1. Start the transaction
SqlMapClient. startTransaction ();

/** Specific event handling **/
// A. query two accounts in the database
Account a = (Account) sqlMapClient. queryForObject ("account_select", aname );
Account B = (Account) sqlMapClient. queryForObject ("account_select", bname );

If (! = Null & B! = Null ){
// B. Set the account amount
A. setMoney (a. getMoney ()-money); // reduce the amount of a account
B. setMoney (B. getMoney () + money); // increase the amount in account B

// C. Execute the transfer function
Int ak = sqlMapClient. update ("account_update", );
Int bk = sqlMapClient. update ("account_update", B );
If (ak! = 1 | bk! = 1 ){
Throw new SQLException ("Transfer failed ");
}

} Else {
Throw new SQLException ("incorrect account information entered ");
}

System. out. println ("transfer successful: Account" + aname + "has been successfully transferred to account" + bname +. \ N transfer amount: "+ money );
// 2. Submit the transaction
SqlMapClient. commitTransaction ();

} Finally {
// 3. End the transaction
SqlMapClient. endTransaction ();
}
}

/**
* Transfer Function [transaction control not implemented]
* @ Param aname
* @ Param bname
* @ Param money
* @ Throws SQLException
*/
Private void exchange1 (String aname, String bname, int money) throws SQLException {

SqlMapClient sqlMapClient = BaseDAO. getInstance ();

Try {
// A. query two accounts in the database
Account a = (Account) sqlMapClient. queryForObject ("account_select", aname );
Account B = (Account) sqlMapClient. queryForObject ("account_select", bname );

// Account a transfers money
A. setMoney (a. getMoney ()-money );
SqlMapClient. update ("account_update", );

// Account B's execution amount
B. setMoney (B. getMoney () + money );
SqlMapClient. update ("account_update", B );


System. out. println ("transfer successful: Account" + aname + "has been successfully transferred to account" + bname +. \ N transfer amount: "+ money );
} Catch (Exception e ){
Throw new SQLException ("Transfer failed ");
}
}
}


Through the test, we can find that data inconsistency does not occur through transaction control. Second, data correctness cannot be guaranteed in the case of exceptions that do not pass transaction control.

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.