事务管理
1.项目目录
book包—>使用注解管理事务
book_xml—>使用xml方式管理事务
数据库表(book,stock,money)
2.使用注解管理事务
2.1 BookController.java
package com.atguigu.book.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.atguigu.book.service.BookService;
import com.atguigu.book.service.Cashier;
@Controller
public class BookController {
@Autowired
private BookService service;
@Autowired
private Cashier cashier;
public void buyBook(){
service.buyBook("1", "1001");
}
public void checkOut(){
List<String> bids = new ArrayList<>();
bids.add("1");
bids.add("2");
cashier.checkOut("1001", bids);
}
}
2.2 BookDao.java
package com.atguigu.book.dao;
public interface BookDao {
Integer selectPrice(String bid);
void updateSt(String bid);
void updateBalance(String uid, Integer price);
}
2.3 BookDaoImpl.java
package com.atguigu.book.dao.impl;
import javax.management.RuntimeErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.atguigu.book.dao.BookDao;
import com.atguigu.book.exception.MyException;
@Repository
public class BookDaoImpl implements BookDao{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public Integer selectPrice(String bid) {
String sql = "select price from book where bid = ?";
Integer price = jdbcTemplate.queryForObject(sql, new Object[]{bid}, Integer.class);
return price;
}
@Override
public void updateSt(String bid) {
//获取该书记的库存
String sql = "select st from stock where sid = ?";
Integer st = jdbcTemplate.queryForObject(sql, new Object[]{bid}, Integer.class);
if(st <= 0){
throw new RuntimeException();
}else{
jdbcTemplate.update("update stock set st = st - 1 where sid = ?", bid);
}
}
@Override
public void updateBalance(String uid, Integer price) {
Integer balance = jdbcTemplate.queryForObject("select balance from money where uid = ?", new Object[]{uid}, Integer.class);
if(balance < price){
throw new MyException("余额不足");
}else{
jdbcTemplate.update("update money set balance = balance - ? where uid = ?", price, uid);
}
}
}
2.4 BookService.java
package com.atguigu.book.service;
public interface BookService {
void buyBook(String bid, String uid);
}
2.5 BookServiceImpl.java
package com.atguigu.book.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.atguigu.book.dao.BookDao;
import com.atguigu.book.exception.MyException;
import com.atguigu.book.service.BookService;
@Service
//@Transactional
public class BookServiceImpl implements BookService{
@Autowired
private BookDao dao;
/**
* @Transactional:对方法中所有的操作作为一个事务进行管理
* 在方法上使用,只对方法有效果
* 在类上使用,对类中所有的方法都有效果
* @Transactional中可以设置的属性:
* propagation:A方法和B方法都有事务,当A在调用B时,会将A中的事务传播给B方法,
* B方法对于事务的处理方式就是事务的传播行为
* Propagation.REQUIRED:必须使用调用者的事务(默认值)
* Propagation.REQUIRES_NEW:将调用者的事务挂起,不使用调用者的事务,使用新的事务进行处理
* isolation:事务的隔离级别,在并发的情况下,操作数据的一种规定
* 读未提交(1):脏读(读到没有意义的数据)--->对于字段来说
* 读已提交(2):不可重复读(重复读到的数据不一致)--->对于字段来说
* 可重复读(4):幻读(重复读到整张表的数据不一致,第一次读一部分,第二次读多了一些数据)--->对于记录来说
* 串行化(8):性能低,消耗大
* timeout:在事务强制回滚前最多可以执行(等待)的时间
*
* readOnly:指定当前事务中的一系列的操作是否为只读
* 若设置为只读,不管事务中有没有写的操作,MySQL都会在请求访问数据的时候,不加锁,提高性能
* 如果有写操作的情况,建议一定不能设置只读
*
* rollbackFor|rollbackForClassName|noRollbackFor|noRollbakForClassName
*/
@Transactional(propagation=Propagation.REQUIRES_NEW, timeout=3, noRollbackFor={NullPointerException.class, MyException.class})
public void buyBook(String bid, String uid){
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
Integer price = dao.selectPrice(bid);
dao.updateSt(bid);
dao.updateBalance(uid, price);
}
}
2.6 Cashier.java
package com.atguigu.book.service;
import java.util.List;
public interface Cashier {
void checkOut(String uid, List<String> bids);
}
2.7 CashierServiceImpl.java
package com.atguigu.book.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.atguigu.book.service.BookService;
import com.atguigu.book.service.Cashier;
@Service
@Transactional
public class CashierServiceImpl implements Cashier{
@Autowired
private BookService service;
@Override
public void checkOut(String uid, List<String> bids) {
// TODO Auto-generated method stub
for (String bid : bids) {
service.buyBook(bid, uid);
}
}
}
2.8 MyException.java
package com.atguigu.book.exception;
public class MyException extends RuntimeException{
public MyException() {
super();
// TODO Auto-generated constructor stub
}
public MyException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
super(arg0, arg1, arg2, arg3);
// TODO Auto-generated constructor stub
}
public MyException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public MyException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public MyException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
}
2.9 Test.java
package com.atguigu.book;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.atguigu.book.controller.BookController;
public class Test {
public static void main(String[] args){
ApplicationContext ac = new ClassPathXmlApplicationContext("book.xml");
BookController controller = ac.getBean("bookController", BookController.class);
controller.buyBook();
//controller.checkOut();
}
}
2.10 db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=root
2.11 book.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-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="com.atguigu.book"></context:component-scan>
<!-- 引入属性文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="db.properties"></property>
</bean>
<!-- 引入属性文件 -->
<context:property-placeholder location="db.properties"/>
<!-- 创建数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 通过数据源配置JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 开启注解驱动,即对事务相关的注解进行扫描,解析含义并执行功能 -->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
</beans>
3.使用xml方式管理事务
3.1 BookServiceImpl.java
package com.atguigu.book_xml.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.atguigu.book_xml.dao.BookDao;
import com.atguigu.book_xml.exception.MyException;
import com.atguigu.book_xml.service.BookService;
@Service
public class BookServiceImpl implements BookService{
@Autowired
private BookDao dao;
public void buyBook(String bid, String uid){
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
Integer price = dao.selectPrice(bid);
dao.updateSt(bid);
dao.updateBalance(uid, price);
}
}
3.2 book_xml.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"
xmlns:aop="http://www.springframework.org/schema/aop"
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-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/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<context:component-scan base-package="com.atguigu.book_xml"></context:component-scan>
<!-- 引入属性文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="db.properties"></property>
</bean>
<!-- 引入属性文件 -->
<context:property-placeholder location="db.properties"/>
<!-- 创建数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 通过数据源配置JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器(相当于一个切面),不管时用注解方式或xml方式配置事务,一定要有DataSourceTransactionManager事务管理器的支持 -->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务通知 -->
<tx:advice id="tx" transaction-manager="dataSourceTransactionManager">
<tx:attributes>
<!-- 在设置好的切入点表达式下再次进行事务设置 -->
<tx:method name="buyBook"/>
<tx:method name="checkOut"/>
<!-- 只有select开头的方法才会被事务处理 -->
<tx:method name="select*" read-only="true"/>
<tx:method name="insert*"/>
<tx:method name="update*"/>
<tx:method name="delete*"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 配置切入点表达式 -->
<aop:config>
<aop:pointcut expression="execution(* com.atguigu.book_xml.service.impl.*.*(..))" id="pointCut"/>
<aop:advisor advice-ref="tx" pointcut-ref="pointCut"/>
</aop:config>
</beans>
3.3 Test.java
package com.atguigu.book_xml;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.atguigu.book_xml.controller.BookController;
public class Test {
public static void main(String[] args){
ApplicationContext ac = new ClassPathXmlApplicationContext("book_xml.xml");
BookController controller = ac.getBean("bookController", BookController.class);
controller.buyBook();
//controller.checkOut();
}
}
3.4 其他代码与注解方式管理事务相同