How to handle the transaction operations of Spring, Ibatis combined with MySQL database usage

Source: Internet
Author: User
Tags aop

Ibatis is the predecessor of MyBatis, which is an open source persistence layer framework. At its core, sqlmap--maps the entity bean to the relational database, separating the business code from the writing of the SQL statement. Ibatis is the "semi-automated" ORM persistence layer framework. This "semi-automation" is the "fully automated" ORM implementation that provides a comprehensive database encapsulation mechanism relative to hibernate, and the "fully automatic" ORM implements the mapping between the Pojo and the database table fields and enables the automatic generation and execution of SQL. The focus of Ibatis is the mapping between Pojo and SQL, which means that Ibatis does not automatically generate and execute SQL for programmers at run time, and specific SQL statements need to be written by programmers. The parameters required by the SQL statement and the returned result fields are then mapped to the specified Pojo through the mapping configuration file. This blog demonstrates how to handle the transaction operations of Spring, Ibatis combined with MySQL database use:

Engineering structures such as:


As this example introduces the more comprehensive, the file is more, here only the marked three files in the code, the full source can be downloaded by clicking the hyperlink at the bottom of this article:

Code in the Bankcarddao.java file:

Package Com.ghj.dao.imp;import Java.sql.sqlexception;import Java.util.hashmap;import java.util.map;import Org.springframework.orm.ibatis.support.sqlmapclientdaosupport;import Org.springframework.transaction.annotation.transactional;import com.ghj.dao.ibankcarddao;/** * Bank card Management data Access Layer Interface implementation class * * @  Author Gao Yingjie */public class Bankcarddao extends Sqlmapclientdaosupport implements Ibankcarddao {/** * transfer * @param outaccount Transfer out account * @param inaccount Transfer account * @param amountofmoney amount * * @author Gao Yingjie */@Override @Transactional//The transaction operation is implemented using annotations Publi C Boolean transferaccounts (String Outaccount, String inaccount, long Amountofmoney) {try {long outaccountdeposit = FINDDEP Ositbyaccount (Outaccount);//Transfer out account of deposit long inaccountdeposit = Finddepositbyaccount (Inaccount);//Deposit into account if ( Updatedepositbyaccount (Outaccountdeposit-amountofmoney, Outaccount)) {//Update transfer account deposit Updatedepositbyaccount ( Inaccountdeposit + Amountofmoney, inaccount);//update transfer account Deposit//outaccount = null;//system.out.println (OutAccount.equals ( Inaccount));//intentionally abnormal to testRetry whether the transaction rolls back}return true;} catch (SQLException e) {System.err.println ("Transfer failed, transaction rollback"); E.printstacktrace ();} return false;} /** * Deposit Enquiry * @param Deposit Deposit * * @author Gao Yingjie */private long Finddepositbyaccount (String account) throws Sqlexceptio N{return (Long) getsqlmapclienttemplate (). queryForObject ("Finddepositbyaccount", account);} /** * Update deposit based on account * @param deposit deposit * @param account * * @author Gao Yingjie */private boolean updatedepositbyaccount (Long Depo Sit, String account) throws Sqlexception{map<string, object> params = new hashmap<string, object> (); Params.put ("deposit", deposit);p arams.put ("account", account), return Getsqlmapclienttemplate (). Update (" Updatedepositbyaccount ", params) > 0;}}

Code in the Application-context.xml file:

<?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:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans http:/ /www.springframework.org/schema/beans/spring-beans-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://w Ww.springframework.org/schema/aop/spring-aop-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/HTTP Www.springframework.org/schema/tx/spring-tx-3.1.xsd "default-autowire=" ByName "default-lazy-init=" false ">< Bean id= "DataSource" class= "Com.mchange.v2.c3p0.ComboPooledDataSource" lazy-init= "false" destroy-method= "close" ><property name= "Driverclass" value= "Com.mysql.jdbc.Driver" ></property><property name= "JdbcUrl" Value= "Jdbc:mysql://127.0.0.1:3306/test?characterencoding=utf-8" ></property><property naMe= "User" value= "root" ></property><property name= "password" value= "" ></property><property Name= "Acquireincrement" value= "5" ></property><property name= "Initialpoolsize" value= "5" ></ Property><property name= "Minpoolsize" value= "5" ></property><property name= "maxPoolSize" value= " "></property><property name=" maxstatements "value=" ></property><property name= " Numhelperthreads "value=" ten "></property><property name=" MaxIdleTime "value=" ></property> </bean> <bean id= "sqlmapclient" class= "Org.springframework.orm.ibatis.SqlMapClientFactoryBean" > < Property name= "Configlocation" > <value>classpath:config/sqlMapConfig.xml</value> </pro perty> <property name= "DataSource" ref= "DataSource"/></bean><bean id= "Bankcarddao" class= " Com.ghj.dao.imp.BankCardDao "> <property name=" sqlmapclient "> <ref bean=" sqlmapcliEnt "/> </property></bean><!--Spring Configure transactional operations: There are several ways to implement transactional operations in spring, which are most commonly used in annotations, This way you need to add a @transactional comment---<bean id= "Datasourcetransactionmanager" class= "on the method that needs to configure the transaction operation Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <property name=" DataSource "ref=" DataSource "/> </bean><tx:annotation-driven transaction-manager=" Datasourcetransactionmanager "/> </beans>

Code in the Bankcard.xml file:

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE sqlmap Public "-//ibatis.apache.org//dtd SQL Map 2.0//en" "Http://ibatis.apache.org/dtd/sql-map-2.dtd" > <sqlMap><!--Account Enquiry Deposit--><select id= "Finddepositbyaccount" parameterclass= "string" resultclass= "long ">select deposit from Lm_bank_card where account= #account # </select><!--Update deposit by account--><update id=" Updatedepositbyaccount "parameterclass=" Java.util.HashMap ">        update lm_bank_card set deposit= #deposit # where account= #account # </update></sqlMap>

" 0 min Download the sample code "

How to handle the transaction operations of Spring, Ibatis combined with MySQL database usage

Related Article

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.