Operations on database transactions in Javaweb

Source: Internet
Author: User
Tags tomcat server

For working with JDBC, use the Setautocommit (false) method of the connection class to open transactions, and commit () to commit transactions.

Because of the design model of the three-tier architecture, the logic of the transaction must be in the service layer, and the DAO layer simply provides a simple crud operation, so the service must get the connection and open the transaction, and pass this connection to the DAO layer for operation. Commits a transaction at the service layer.

Passing the connection to the DAO layer can be passed in as a parameter when the DAO layer method (or constructor) is called, but this will not only pollute the method signature of the DAO layer, but also make the method call look long and smelly for multi-layered parameter passing. The following method of parameter passing with the Threadlocal container is much more elegant:

① for a Tomcat server, each HTTP request is assigned to a thread to process, the thread can be a new thread, or it can be fetched from the thread pool. and a single request is done in the same thread.

The ②threadlocal can store an object with the current thread as key and the corresponding object with the current thread as key.

In the same thread we coexist a connection open transaction to threadlocal in the service layer, and the code runs to the DAO layer's Update method to get the connection in threadlocal (its reference). Using this connection to manipulate the database, the method returns to the service layer after we get the connection from the threadlocal, commits the transaction, and clears the Threadlocal container .

The code is as follows:

1.dao Layer Code:

 Packagecom.hao.utils;ImportJavax.naming.Context;ImportJavax.naming.InitialContext;Importjavax.naming.NamingException;ImportJavax.sql.DataSource;Importjava.sql.Connection;Importjava.sql.SQLException; Public classDaoutils {Private StaticDataSource ds; Private StaticThreadlocal<connection> connectionthreadlocal =NewThreadlocal<>(); Static {        Try{Context Initctx=NewInitialContext (); Context Envctx= (Context) initctx.lookup ("Java:comp/env")); DS= (DataSource) envctx.lookup ("Jdbc/employeedb"); } Catch(namingexception e) {Throw NewExceptionininitializererror (e); }    }//opens a transaction that binds a link to an open transaction to the thread, which is called to the service layer     Public Static voidStartTransaction () {Try{Connection conn=ds.getconnection (); Conn.setautocommit (false);        Connectionthreadlocal.set (conn); } Catch(SQLException e) {Throw NewRuntimeException (e); }    }    //get the transaction link, remove the link from the thread, which is used for the DAO layer     Public StaticConnection gettransactionconnection () {returnConnectionthreadlocal.get (); }    //commit the transaction, unbind the connection from the thread, which is used for the service layer     Public Static voidcommittransaction () {Try{Connection conn=Connectionthreadlocal.get ();        Conn.commit (); } Catch(SQLException e) {Throw NewRuntimeException (e); } finally {            //since the connectionthreadlocal is static, it will always exist after loading in the server, and the load must be emptied by itself .Connectionthreadlocal.remove (); }    }}
 PackageCom.hao.dao;ImportCom.hao.domain.Account;Importcom.hao.utils.DaoUtils;ImportOrg.apache.commons.dbutils.QueryRunner;ImportOrg.apache.commons.dbutils.handlers.BeanHandler;Importjava.sql.SQLException; Public classAccountdao {PrivateQueryrunner QR =NewQueryrunner ();  Public voidAdd (Account account) {String SQL= "INSERT into account (Id,name,money) VALUES (?,?,?)"; Try{qr.update (SQL, Account.getid (), Account.getname (), Account.getmoney ()); } Catch(SQLException e) {Throw NewRuntimeException (e); }    }     Public voidDelete (string id) {String sql= "Delete from account where id =?"; Try{qr.update (SQL, id); } Catch(SQLException e) {Throw NewRuntimeException (e); }    }     Public voidUpdate (account account) {String SQL= "Update account set name=?,money=?" where id=? "; Try {            //use a link to open a transaction when updatingqr.update (daoutils.gettransactionconnection (), SQL, Account.getname (), Account.getmoney (), Account.getid ()        ); } Catch(SQLException e) {Throw NewRuntimeException (e); }    }     PublicAccount Find (String id) {String sql= "Select Name,money from account where id=?"; Try{ Account account= Qr.query (SQL,NewBeanhandler<account> (account.class), id);            Account.setid (ID); returnAccount ; } Catch(SQLException e) {Throw NewRuntimeException (e); }    }}

2.service Layer Code:

 PackageCom.hao.service;ImportCom.hao.dao.AccountDao;ImportCom.hao.domain.Account;Importcom.hao.utils.DaoUtils; Public classBusinessservice { Public voidTransfer (string SourceID, String Targetid,DoubleMoney ) {        //Open Transactiondaoutils.starttransaction (); //Start TransferAccountdao DAO =NewAccountdao (); Account Sourceaccount=Dao.find (SourceID); Sourceaccount.setmoney (Sourceaccount.getmoney ()-Money );        Dao.update (Sourceaccount); Account Targetaccount=Dao.find (Targetid); Targetaccount.setmoney (Targetaccount.getmoney ()+Money );        Dao.update (Targetaccount); //Commit a transactiondaoutils.committransaction (); //Note that the above actions are in the same thread    }}

Operations on database transactions in Javaweb

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.