用来确保数据的完整性和一致性.
事务的四个关键属性(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_person jdbc.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); //更新书的库存,使书号对应的库存-1 public void updateBookStock(String isbn); //更新账户余额 使username的balance-price public 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 { @Autowired private JdbcTemplate jdbcTemplate; @Override public double findPriceByIsbn(String isbn) { String sql = "SELECT price FROM book WHERE isbn = ?"; return jdbcTemplate.queryForObject(sql, Double.class, isbn); } @Override public 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); } @Override public 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{ @Autowired private BookShopDAO bookShopDAO; //添加事务注解 @Transactional @Override public 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>