JavaEE——Spring4--(9)Spring的事务管理(注解方式)
用來確保數據的完整性和一致性.
事務的四個關鍵屬性(ACID)
原子性(atomicity): 事務是一個原子操作, 由一系列動作組成. 事務的原子性確保動作要么全部完成要么完全不起作用.
一致性(consistency): 一旦所有事務動作完成, 事務就被提交. 數據和資源就處于一種滿足業務規則的一致性狀態中.
隔離性(isolation): 可能有許多事務會同時處理相同的數據, 因此每個事物都應該與其他事務隔離開來, 防止數據損壞.
持久性(durability): 一旦事務完成, 無論發生什么系統錯誤, 它的結果都不應該受到影響. 通常情況下, 事務的結果被寫到持久化存儲器中.
?
1.基于注解的
導入相應的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><!--導入資源文件--><context:property-placeholder location="classpath:db.properties"/><!--配置C3P0數據源--><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>相應的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配置了這個標簽后,spring可以自動去掃描base-pack下面或者子包下面的java文件,如果掃描到有@Component @Controller@Service等這些注解的類,則把這些類注冊為bean
再寫出連接數據庫后需要做的事情(增刪改查)
1.寫增刪改查的接口
package jdbc.transactionManager;public interface BookShopDAO {//根據書號獲取單價public double findPriceByIsbn(String isbn);//更新書的庫存,使書號對應的庫存-1public void updateBookStock(String isbn);//更新賬戶余額 使username的balance-pricepublic void updateUserAccount(String username, double price); }實現增刪改查接口
記得在實現的類上標上注解@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? 然后寫全部的構造器
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 );} }進行查詢購買
1.先寫購買的接口
package jdbc.transactionManager;public interface BookShopService {//顧客買書public void purchase(String username, String isbn); }
2.在實現該接口? ?在實現該購買接口時,注意在對應的方法上面添上事務注解@Transactional
這樣購買的流程就會成為一個事務,當余額或庫存不足時,不會完成事務,會發生回滾
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;//添加事務注解@Transactional@Overridepublic void purchase(String username, String isbn) {//獲取書的單價double price = bookShopDAO.findPriceByIsbn(isbn);//更新書的庫存bookShopDAO.updateBookStock(isbn);//更新用戶的余額bookShopDAO.updateUserAccount(username, price);} }注意還要在xml中進行事務配置
<!--配置事務管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!--啟用事務注解--><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><!--導入資源文件--><context:property-placeholder location="classpath:db.properties"/><!--配置C3P0數據源--><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><!--配置事務管理器--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!--啟用事務注解--><tx:annotation-driven transaction-manager="transactionManager"/></beans>
?
轉載于:https://www.cnblogs.com/SkyeAngel/p/8306328.html
總結
以上是生活随笔為你收集整理的JavaEE——Spring4--(9)Spring的事务管理(注解方式)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Xshell 使用数字小键盘进行vim
- 下一篇: 防火墙--iptables