Java transaction (3): java transaction

Source: Internet
Author: User

Java transaction (3): java transaction

I. Why ThreadLocal:

In the previous blog, we passed the Connection method to control transactions. This method can achieve the goal, but it is unpleasant to see,

If multiple services are called, do I have to pass the Connection from the controller layer?


For the usage of ThreadLocal, see the previous blog. This class ensures that the instance variables of a class have a separate copy in each thread,

This will not affect instance variables in other threads


Ii. How to Use ThreadLocal:

1. Write a TransactionManager class:

/***** Manage transactions */public class TransactionManager {private static ThreadLocal <Connection> local = new ThreadLocal <Connection> (); // enable the public static void beginTransaction () transaction () throws SQLException {Connection conn = JDBCUtils. getConnection (); conn. setAutoCommit (false); // Save the connection to threadLocallocal. set (conn);} // rollback transaction public static void rollback () throws SQLException {Connection conn = local. get (); if (conn! = Null) {conn. rollback (); conn. close (); // clear threadLocallocal. remove () ;}// submit the transaction public static void commit () throws SQLException {Connection conn = local. get (); if (conn! = Null) {conn. commit (); // clear threadLocallocal. remove () ;}// close the Connection public static void close () throws SQLException {Connection conn = local. get (); if (conn! = Null) {conn. close (); // clear threadLocallocal. remove () ;}// obtain the public static Connection getConnection () {return local. get ();}}
Use ThreadLocal to ensure that the same connection is obtained by the same thread.


2. Modify the business processing class

/*** Business logic layer */public class AccountService {public void transfer (Account outAccount, Account inAccount, int money) throws SQLException {// enable transaction TransactionManager. beginTransaction (); // query two accounts: AccountDAO accountDAO = new AccountDAO (); outAccount = accountDAO. findAccountById (outAccount. getId (); inAccount = accountDAO. findAccountById (inAccount. getId (); // transfer-modify the original account amount outAccount. setMoney (outAccount. getMoney ()-money); inAccount. setMoney (inAccount. getMoney () + money); try {// update the account amount accountDAO. update (outAccount); accountDAO. update (inAccount); // The transfer is successful, and the transaction TransactionManager is submitted. commit ();} catch (Exception e) {// transfer failed, roll back transaction TransactionManager. rollback (); e. printStackTrace ();} finally {// close the connection to TransactionManager. close ();}}}

Using TransactionManager to manage transactions makes the code simpler.


3. Modify Dao class

/*** DAO layer: CRUD */public class AccountDAO {// query the public Account findAccountById (int id) throws SQLException {String SQL = "select * from account where id =? "; Object [] params = {id}; QueryRunner queryRunner = new QueryRunner (JDBCUtils. getDataSource (); return queryRunner. query (SQL, new BeanHandler <Account> (Account. class), params);} // update the public void update (Account account) throws SQLException {String SQL = "update account set name = ?, Money =? Where id =? "; Object [] params = {account. getName (), account. getMoney (), account. getId ()}; // obtain the Connection from threadLocal. The same thread obtains the Connection conn = TransactionManager. getConnection (); QueryRunner queryRunner = new QueryRunner (); queryRunner. update (conn, SQL, params );}}

You do not need to pass the Connection. You can directly obtain the Connection from TransactionManager.


Iii. Summary:

Both service and dao use TransactionManager to obtain the Connection. In the same thread, they use the same Connection object throughout the transaction processing process, so the transaction will be processed successfully, dao does not accept objects unrelated to the business, eliminating api pollution. In addition, TransactionManager is used to manage transactions, simplifying the service-layer code.



In java transactions

Here is a detailed description of mianshi.fenzhi.com/post/522.html !!

Java Transaction Processing

If you perform multiple operations on the database, each execution or step is a transaction. if the database operation is not executed at a certain step or the transaction fails due to an exception, some transactions will not be executed and the transaction will be rolled back, cancel previous operations .....
Use JDBC to process transactions in JavaBean

Public int delete (int sID ){
Dbc = new DataBaseConnection ();
Connection con = dbc. getConnection ();
Try {
Con. setAutoCommit (false); // change the default commit method of JDBC transactions
Dbc.exe cuteUpdate ("delete from xiao where ID =" + sID );
Dbc.exe cuteUpdate ("delete from xiao_content where ID =" + sID );
Dbc.exe cuteUpdate ("delete from xiao_affix where bylawid =" + sID );
Con. commit (); // submit a JDBC transaction
Con. setAutoCommit (true); // restore the default commit Method for JDBC transactions
Dbc. close ();
Return 1;
}
Catch (Exception exc ){
Con. rollBack (); // roll back JDBC transactions
Exc. printStackTrace ();
Dbc. close ();
Return-1;
}
}

In database operations, a transaction is an inseparable unit of work consisting of one or more SQL statements updated to the database. The entire transaction can be committed to the database only when all operations in the transaction are completed normally. If one operation is not completed, the entire transaction must be canceled.

For example, in a bank transfer transaction, assume that Michael Jacob transfers 1000 yuan from his account to Mr. Li's account. The related SQL statement is as follows:

Update account set monery = monery-1000 where name = 'hangsan'

Update account set monery = monery + 1000 where name = 'lisi'

The two statements must be processed as a completed transaction. This transaction can be committed only when both are successfully executed. If one sentence fails, the entire transaction must be undone.

The connection class provides three methods to control transactions:

(1) setAutoCommit (Boolean autoCommit): sets whether to automatically submit transactions;

(2) commit (); Submit a transaction;

(3) rollback (); undo the transaction;

In the jdbc api, the default situation is automatic transaction commit. That is to say, each SQL statement updated to the database represents a transaction. After the operation is successful, the system automatically calls commit () otherwise, rollback () is called to cancel the transaction.

In the jdbc api, you can call setAutoCommit (false) to disable automatic commit of transactions. Then, you can use multiple SQL statements for updating the database as a transaction. After all the operations are completed, you can call com... the remaining full text>
 

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.