您好,登錄后才能下訂單哦!
在企業(yè)級(jí)應(yīng)用中,保護(hù)數(shù)據(jù)的完整性是非常重要的一件事。因此不管應(yīng)用的性能是多么的高、界面是多么的好看,如果在轉(zhuǎn)賬的過程中出現(xiàn)了意外導(dǎo)致用戶的賬號(hào)金額發(fā)生錯(cuò)誤,那么這樣的應(yīng)用程序也是不可接受的
數(shù)據(jù)庫的事務(wù)管理可以有效地保護(hù)數(shù)據(jù)的完整性(PS:關(guān)于數(shù)據(jù)庫的事務(wù)管理基礎(chǔ)可以參考我以前寫過的這篇文章:http://www.zifangsky.cn/385.html),但是原生態(tài)的事務(wù)操作需要寫不少的代碼,無疑是非常麻煩的。在使用了Spring框架的應(yīng)用中,我們可以使用@Transactional 注解方便地進(jìn)行事務(wù)操作,如事務(wù)的回滾等。接下來我將以SSM框架中的事務(wù)注解操作進(jìn)行舉例說明:
(1)項(xiàng)目結(jié)構(gòu)和用到的jar包:
(2)測試使用到的SQL文件:
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for user -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(32) DEFAULT NULL, `password` varchar(64) DEFAULT NULL, `email` varchar(64) DEFAULT NULL, `birthday` date DEFAULT NULL, `money` decimal(15,2) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', 'admin', '123456', 'admin@qq.com', '2000-01-02', '1000.00'); INSERT INTO `user` VALUES ('2', 'test', '1234', 'test@zifangsky.cn', '1990-12-12', '2500.00'); INSERT INTO `user` VALUES ('3', 'xxxx', 'xx', 'xx@zifangsky.cn', '1723-06-21', '4000.00');
(3)使用mybatis-generator結(jié)合Ant腳本快速自動(dòng)生成Model、Mapper等文件:
關(guān)于這方面可以參考我以前寫過的一篇文章,這里就不多說了,傳送門:http://www.zifangsky.cn/431.html
(4)一些基礎(chǔ)配置文件:
i)web.xml:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:context/context.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:context/jsp-dispatcher.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
ii)jdbc配置文件jdbc.properties:
master.jdbc.driverClassName=com.mysql.jdbc.Driver master.jdbc.url=jdbc:mysql://127.0.0.1:3306/transaction #user master.jdbc.username=root master.jdbc.password=root
iii)context.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"> <context:component-scan base-package="cn.zifangsky.dao" annotation-config="true" /> <context:component-scan base-package="cn.zifangsky.manager" annotation-config="true" /> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <!-- 配置數(shù)據(jù)源 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass"> <value>${master.jdbc.driverClassName}</value> </property> <property name="jdbcUrl"> <value>${master.jdbc.url}</value> </property> <property name="user"> <value>${master.jdbc.username}</value> </property> <property name="password"> <value>${master.jdbc.password}</value> </property> <!--連接池中保留的最小連接數(shù)。 --> <property name="minPoolSize"> <value>5</value> </property> <!--連接池中保留的最大連接數(shù)。Default: 15 --> <property name="maxPoolSize"> <value>30</value> </property> <!--初始化時(shí)獲取的連接數(shù),取值應(yīng)在minPoolSize與maxPoolSize之間。Default: 3 --> <property name="initialPoolSize"> <value>10</value> </property> <!--最大空閑時(shí)間,60秒內(nèi)未使用則連接被丟棄。若為0則永不丟棄。Default: 0 --> <property name="maxIdleTime"> <value>60</value> </property> <!--當(dāng)連接池中的連接耗盡的時(shí)候c3p0一次同時(shí)獲取的連接數(shù)。Default: 3 --> <property name="acquireIncrement"> <value>5</value> </property> <!--JDBC的標(biāo)準(zhǔn)參數(shù),用以控制數(shù)據(jù)源內(nèi)加載的PreparedStatements數(shù)量。但由于預(yù)緩存的statements 屬于單個(gè) connection而不是整個(gè)連接池。所以設(shè)置這個(gè)參數(shù)需要考慮到多方面的因素。 如果maxStatements與maxStatementsPerConnection均為0,則緩存被關(guān)閉。Default: 0 --> <property name="maxStatements"> <value>0</value> </property> <!--每60秒檢查所有連接池中的空閑連接。Default: 0 --> <property name="idleConnectionTestPeriod"> <value>60</value> </property> <!--定義在從數(shù)據(jù)庫獲取新連接失敗后重復(fù)嘗試的次數(shù)。Default: 30 --> <property name="acquireRetryAttempts"> <value>30</value> </property> <!--獲取連接失敗將會(huì)引起所有等待連接池來獲取連接的線程拋出異常。但是數(shù)據(jù)源仍有效 保留,并在下次調(diào)用 getConnection()的時(shí)候繼續(xù)嘗試獲取連接。如果設(shè)為true,那么在嘗試 獲取連接失敗后該數(shù)據(jù)源將申明已斷開并永久關(guān)閉。Default: false --> <property name="breakAfterAcquireFailure"> <value>true</value> </property> <!--因性能消耗大請(qǐng)只在需要的時(shí)候使用它。如果設(shè)為true那么在每個(gè)connection提交的 時(shí)候都將校驗(yàn)其有效性。建議 使用idleConnectionTestPeriod或automaticTestTable 等方法來提升連接測試的性能。Default: false --> <property name="testConnectionOnCheckout"> <value>false</value> </property> </bean> <!-- SqlMap setup for iBATIS Database Layer --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:context/sql-map-config.xml" /> <property name="dataSource" ref="dataSource" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.zifangsky.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean> <!-- Transaction manager for a single JDBC DataSource --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- 開啟注解方式聲明事務(wù) --> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
在上面的配置中,使用了C3P0作為數(shù)據(jù)庫連接池,同時(shí)定義了自動(dòng)掃描注解,Mybatis相關(guān)配置以及申明式事務(wù)管理,如果對(duì)這些基礎(chǔ)不太熟的話可以參考下我以前寫過的一些文章
iv)jsp-dispatcher.xml:
<?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:context="http://www.springframework.org/schema/context" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd" default-lazy-init="true"> <mvc:annotation-driven /> <context:annotation-config /> <!-- 激活Bean中定義的注解 --> <!-- 啟動(dòng)自動(dòng)掃描該包下所有的Bean(例如@Controller) --> <context:component-scan base-package="cn.zifangsky.controller" annotation-config="true" /> <!-- 定義視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
v)sql-map-config.xml:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <!-- 全局的映射器啟用或禁用緩存。 --> <setting name="cacheEnabled" value="true" /> <!-- 全局啟用或禁用延遲加載 --> <setting name="lazyLoadingEnabled" value="true" /> <!-- 允許或不允許多種結(jié)果集從一個(gè)單獨(dú)的語句中返回 --> <setting name="multipleResultSetsEnabled" value="true" /> <!-- 使用列標(biāo)簽代替列名 --> <setting name="useColumnLabel" value="true" /> <!-- 允許JDBC支持生成的鍵 --> <setting name="useGeneratedKeys" value="false" /> <!-- 配置默認(rèn)的執(zhí)行器 --> <setting name="defaultExecutorType" value="SIMPLE" /> <!-- 設(shè)置超時(shí)時(shí)間 --> <setting name="defaultStatementTimeout" value="25000" /> </settings> <mappers> <mapper resource="sqlmaps/UserMapper.xml" /> </mappers> </configuration>
(5)測試搭建的項(xiàng)目環(huán)境:
i)在UserManager.java接口中添加幾個(gè)基本的接口:
public interface UserManager { int deleteByPrimaryKey(Integer id); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
ii)UserManagerImpl.java:
package cn.zifangsky.manager.impl; import java.math.BigDecimal; import javax.annotation.Resource; import org.apache.ibatis.jdbc.RuntimeSqlException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.zifangsky.manager.UserManager; import cn.zifangsky.mapper.UserMapper; import cn.zifangsky.model.User; @Service(value="userManagerImpl") public class UserManagerImpl implements UserManager{ @Resource(name="userMapper") private UserMapper userMapper; public int deleteByPrimaryKey(Integer id) { return 0; } public int insert(User record) { return 0; } public int insertSelective(User record) { return 0; } public User selectByPrimaryKey(Integer id) { return userMapper.selectByPrimaryKey(id); } public int updateByPrimaryKeySelective(User record) { return 0; } public int updateByPrimaryKey(User record) { return 0; } }
iii)UserController.java:
package cn.zifangsky.controller; import java.math.BigDecimal; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import cn.zifangsky.manager.UserManager; import cn.zifangsky.model.User; @Controller public class UserController { @Resource(name = "userManagerImpl") private UserManager userManager; @RequestMapping(value = "/select") public String user(@RequestParam(name = "userId", required = false) Integer userId) { User user = userManager.selectByPrimaryKey(userId); System.out.println("用戶名: " + user.getName()); System.out.println("郵箱: " + user.getEmail()); return "success"; } }
iv)啟動(dòng)項(xiàng)目并進(jìn)行測試:
項(xiàng)目啟動(dòng)后訪問:http://localhost:8090/TransactionDemo/select.html?userId=2 ,如果發(fā)現(xiàn)控制臺(tái)中輸出如下則說明測試環(huán)境已經(jīng)搭建成功了:
用戶名: test 郵箱: test@zifangsky.cn
(1)在UserManager接口中添加一個(gè)如下方法:
/** * 轉(zhuǎn)賬 * * @param sourceAccountId * 源賬戶 * @param targetAccountId * 目標(biāo)賬戶 * @param amount * 轉(zhuǎn)賬金額 */ void transferMoney(Integer sourceAccountId, Integer targetAccountId, BigDecimal amount);
此方法目的是為了模擬轉(zhuǎn)賬操作
(2)在UserManagerImpl實(shí)現(xiàn)類中添加對(duì)用的實(shí)現(xiàn)方法:
@Transactional(rollbackFor=Exception.class) public void transferMoney(Integer sourceAccountId, Integer targetAccountId, BigDecimal amount) { User sourceAccount = userMapper.selectByPrimaryKey(sourceAccountId); User targetAccount = userMapper.selectByPrimaryKey(targetAccountId); BigDecimal sourceMoney = sourceAccount.getMoney(); BigDecimal targetMoney = targetAccount.getMoney(); //判斷賬戶余額是否足夠 if(sourceMoney.compareTo(amount) > 0){ sourceAccount.setMoney(sourceMoney.subtract(amount)); targetAccount.setMoney(targetMoney.add(amount)); //更新數(shù)據(jù)庫 userMapper.updateByPrimaryKeySelective(sourceAccount); throw new RuntimeSqlException("手動(dòng)模擬轉(zhuǎn)賬時(shí)出現(xiàn)異常"); // userMapper.updateByPrimaryKeySelective(targetAccount); } }
可以看出,在這個(gè)方法上面申明了一個(gè)@Transactional,表明這個(gè)方法將要進(jìn)行事務(wù)管理,同時(shí)需要說明的是rollbackFor參數(shù)定義了在出現(xiàn)了什么異常時(shí)進(jìn)行事務(wù)的回滾,顯然這里定義的就是所有的Exception都要進(jìn)行事務(wù)回滾。與之相反的一個(gè)參數(shù)是norollbackFor,這里就不多說了。對(duì)于@Transactional注解我們不僅可以在一個(gè)方法上放置,而且可以在類上進(jìn)行申明。如果在類級(jí)別上使用該注解,那么類中的所有公共方法都被事務(wù)化,否則就只有使用了@Transactional注解的公共方法才被事務(wù)化
在這個(gè)方法中為了模擬轉(zhuǎn)賬出現(xiàn)異常,因此在第一個(gè)賬戶進(jìn)行更新后就手動(dòng)拋出了一個(gè)異常
(3)在UserController類中添加一個(gè)模擬轉(zhuǎn)賬的方法:
@RequestMapping(value = "/transfer") public String transfer(@RequestParam(name = "account1") Integer account1, @RequestParam(name = "account2") Integer account2, @RequestParam(name = "amount") Long amount) { System.out.println("轉(zhuǎn)賬之前:"); System.out.println("賬戶一的資金:" + userManager.selectByPrimaryKey(account1).getMoney().longValue()); System.out.println("賬戶二的資金:" + userManager.selectByPrimaryKey(account2).getMoney().longValue()); // 轉(zhuǎn)賬 userManager.transferMoney(account1, account2, BigDecimal.valueOf(amount)); System.out.println("轉(zhuǎn)賬之后:"); System.out.println("賬戶一的資金:" + userManager.selectByPrimaryKey(account1).getMoney().longValue()); System.out.println("賬戶二的資金:" + userManager.selectByPrimaryKey(account2).getMoney().longValue()); return "success"; }
(4)效果測試:
項(xiàng)目運(yùn)行后訪問:http://localhost:8090/TransactionDemo/transfer.html?account1=1&account2=2&amount=500
可以發(fā)現(xiàn)項(xiàng)目會(huì)進(jìn)行保存,這時(shí)我們查看數(shù)據(jù)庫中看看賬戶1和賬戶2中的金額有沒有發(fā)生變化:
可以看出,兩者的金額都沒有發(fā)生改變,說明事物的確進(jìn)行了回滾。當(dāng)然,有興趣的同學(xué)可以把UserManagerImpl中那個(gè) @Transactional 注解給去掉看看數(shù)據(jù)庫中的這個(gè)金額在執(zhí)行“轉(zhuǎn)賬”后又會(huì)不會(huì)發(fā)生改變?
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。