JavaEE——Spring4--(9)Spring的事务管理(注解方式)
用來確保數(shù)據(jù)的完整性和一致性.
事務(wù)的四個關(guān)鍵屬性(ACID)
原子性(atomicity): 事務(wù)是一個原子操作, 由一系列動作組成. 事務(wù)的原子性確保動作要么全部完成要么完全不起作用.
一致性(consistency): 一旦所有事務(wù)動作完成, 事務(wù)就被提交. 數(shù)據(jù)和資源就處于一種滿足業(yè)務(wù)規(guī)則的一致性狀態(tài)中.
隔離性(isolation): 可能有許多事務(wù)會同時處理相同的數(shù)據(jù), 因此每個事物都應(yīng)該與其他事務(wù)隔離開來, 防止數(shù)據(jù)損壞.
持久性(durability): 一旦事務(wù)完成, 無論發(fā)生什么系統(tǒng)錯誤, 它的結(jié)果都不應(yīng)該受到影響. 通常情況下, 事務(wù)的結(jié)果被寫到持久化存儲器中.
?
1.基于注解的
導(dǎo)入相應(yīng)的jar包? mysql? C3P0? 和Spring的AOP的
<?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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!--掃描包--><context:component-scan base-package="jdbc"></context:component-scan><!--導(dǎo)入資源文件--><context:property-placeholder location="classpath:db.properties"/><!--配置C3P0數(shù)據(jù)源--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="user" value="${jdbc.user}"></property><property name="password" value="${jdbc.password}"></property><property name="driverClass" value="${jdbc.driverClass}"></property><property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property><property name="initialPoolSize" value="${jdbc.initPoolSize}"></property><property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property></bean><!--配置Spring的JDBCTemplate--><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean></beans>相應(yīng)的db.properties
jdbc.user=root jdbc.password=1234 jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql://localhost:3306/db_personjdbc.initPoolSize=5 jdbc.maxPoolSize=10
首先配置組件掃描
<context:component-scan base-package="jdbc"></context:component-scan>
在xml配置了這個標(biāo)簽后,spring可以自動去掃描base-pack下面或者子包下面的java文件,如果掃描到有@Component @Controller@Service等這些注解的類,則把這些類注冊為bean
再寫出連接數(shù)據(jù)庫后需要做的事情(增刪改查)
1.寫增刪改查的接口
package jdbc.transactionManager;public interface BookShopDAO {//根據(jù)書號獲取單價public double findPriceByIsbn(String isbn);//更新書的庫存,使書號對應(yīng)的庫存-1public void updateBookStock(String isbn);//更新賬戶余額 使username的balance-pricepublic void updateUserAccount(String username, double price); }實現(xiàn)增刪改查接口
記得在實現(xiàn)的類上標(biāo)上注解@Repository("bookShopDAO")
還有?@Autowired
?
?
package jdbc.transactionManager;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository;@Repository("bookShopDAO") public class BookShopDAOImpl implements BookShopDAO {@Autowiredprivate JdbcTemplate jdbcTemplate;@Overridepublic double findPriceByIsbn(String isbn) {String sql = "SELECT price FROM book WHERE isbn = ?";return jdbcTemplate.queryForObject(sql, Double.class, isbn);}@Overridepublic void updateBookStock(String isbn) {//要檢查書的庫存是否足夠,不夠的話,要拋出異常String sql2 = "SELECT stock FROM book_stock WHERE isbn = ?";int stock = jdbcTemplate.queryForObject(sql2, Integer.class, isbn);if(stock == 0){throw new BookStockException("庫存不足");}String sql = "UPDATE book_stock SET stock = stock - 1 WHERE isbn = ?";jdbcTemplate.update(sql, isbn);}@Overridepublic void updateUserAccount(String username, double price) {//要檢查用戶的余額,不夠的話,要拋出異常String sql2 = "SELECT balance FROM account WHERE username = ?";double balance = jdbcTemplate.queryForObject(sql2, Double.class, username);if(balance <= price){throw new UserAccountException("余額不足");}String sql = "UPDATE account SET balance = balance - ? WHERE username = ?";jdbcTemplate.update(sql, price, username);} }
注意判斷條件,若不符合條件的拋出異常
自己定義的異常? 首先要繼承RunTimeException? 然后寫全部的構(gòu)造器
package jdbc.transactionManager;public class BookStockException extends RuntimeException {private static final long serialVersionUID = 1L;public BookStockException() {}public BookStockException(String message) {super( message );}public BookStockException(String message, Throwable cause) {super( message, cause );}public BookStockException(Throwable cause) {super( cause );}public BookStockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {super( message, cause, enableSuppression, writableStackTrace );} }進(jìn)行查詢購買
1.先寫購買的接口
package jdbc.transactionManager;public interface BookShopService {//顧客買書public void purchase(String username, String isbn); }
2.在實現(xiàn)該接口? ?在實現(xiàn)該購買接口時,注意在對應(yīng)的方法上面添上事務(wù)注解@Transactional
這樣購買的流程就會成為一個事務(wù),當(dāng)余額或庫存不足時,不會完成事務(wù),會發(fā)生回滾
package jdbc.transactionManager;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;@Service("bookShopService") public class BookShopServiceImpl implements BookShopService{@Autowiredprivate BookShopDAO bookShopDAO;//添加事務(wù)注解@Transactional@Overridepublic void purchase(String username, String isbn) {//獲取書的單價double price = bookShopDAO.findPriceByIsbn(isbn);//更新書的庫存bookShopDAO.updateBookStock(isbn);//更新用戶的余額bookShopDAO.updateUserAccount(username, price);} }注意還要在xml中進(jìn)行事務(wù)配置
<!--配置事務(wù)管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!--啟用事務(wù)注解--><tx:annotation-driven transaction-manager="transactionManager"/>完整的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:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!--掃描包--><context:component-scan base-package="jdbc"></context:component-scan><!--導(dǎo)入資源文件--><context:property-placeholder location="classpath:db.properties"/><!--配置C3P0數(shù)據(jù)源--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="user" value="${jdbc.user}"></property><property name="password" value="${jdbc.password}"></property><property name="driverClass" value="${jdbc.driverClass}"></property><property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property><property name="initialPoolSize" value="${jdbc.initPoolSize}"></property><property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property></bean><!--配置Spring的JDBCTemplate--><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean><!--配置事務(wù)管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!--啟用事務(wù)注解--><tx:annotation-driven transaction-manager="transactionManager"/></beans>
?
轉(zhuǎn)載于:https://www.cnblogs.com/SkyeAngel/p/8306328.html
總結(jié)
以上是生活随笔為你收集整理的JavaEE——Spring4--(9)Spring的事务管理(注解方式)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Xshell 使用数字小键盘进行vim
- 下一篇: 防火墙--iptables