事务
1,什么是事务?
事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败。
2,事务的四个特性
原子性、一致性、隔离性、持久性、
3,Spring事务操作,购买商品为例
(1)使用spring的事务注解管理事务
通过@Transactional 注解方式,可将事务织入到相应 public 方法中,实现事务管理。
@Transactional 的所有可选属性如下所示:
- propagation:用于设置事务传播属性。该属性类型为 Propagation 枚举,默认值为Propagation.REQUIRED
- isolation:用于设置事务的隔离级别。该属性类型为 Isolation 枚举,默认值为Isolation.DEFAULT。
- readOnly:用于设置该方法对数据库的操作是否是只读的。该属性为 boolean,默认值为 false。
- timeout:用于设置本操作与数据库连接的超时时限。单位为秒,类型为 int,默认值为-1,即没有时限。
- rollbackFor:指定需要回滚的异常类。类型为 Class[],默认值为空数组。当然,若只有一个异常类时,可以不使用数组。
- rollbackForClassName:指定需要回滚的异常类类名。类型为 String[],默认值为空数组。当然,若只有一个异常类时,可以不使用数组。
- noRollbackFor:指定不需要回滚的异常类。类型为 Class[],默认值为空数组。当然,若只有一个异常类时,可以不使用数组。
- noRollbackForClassName:指定不需要回滚的异常类类名。类型为 String[],默认值为空数组。当然,若只有一个异常类时,可以不使用数组。
需要注意的是,**@Transactional 若用在方法上,只能用于 public 方法上。**对于其他非 public
方法,如果加上了注解@Transactional,虽然 Spring 不会报错,但不会将指定事务织入到该
方法中。因为 Spring 会忽略掉所有非 public 方法上的@Transaction 注解。
若@Transaction 注解在类上,则表示该类上所有的方法均将在执行时织入事务。
利用注解实现事务的步骤:
适合中小型项目
-
声明事务管理器
<!--声明事务管理器对象:使用 Spring 的事务注解管理事务--> <!--事务:需要告诉spring使用的是那种数据库访问技术 声明事务管理器的实现类: mybatis:DateSourceTransactionManager hibernate:hibernateTransactionManager --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--连接数据库指定数据源--> <property name="dataSource" ref="myDataSource"/> </bean>
-
开启注解驱动
<!--开启事务注解驱动,告诉spring使用注解管理事务,创建代理对象,transaction-manager代表事务管理器--> <tx:annotation-driven transaction-manager="transactionManager"/>
-
在service业务层中的public方法中加入事务属性
//使用spring注解方式来控制事务,适合小型项目 /*@Transactional( //用于设置事务传播属性。该属性类型为 Propagation 枚举,默认值为Propagation.REQUIRED。 propagation=Propagation.REQUIRED, //用于设置事务的隔离级别。该属性类型为 Isolation 枚举,默认值为Isolation.DEFAULT。 isolation= Isolation.DEFAULT, //用于设置该方法对数据库的操作是否是只读的。该属性为 boolean,默认值为 false。 readOnly = false, //发生指定异常时一定回滚,如果在异常之外则运行时异常也会事务回滚 rollbackFor = { NullPointerException.class,NotEnoughException.class } )*/ //直接写注解等价于以上直接设置,开发中常用直接写注解@Transactional就行了 @Transactional @Override public void buy(Integer goodsId, Integer nums) { //记录销售订单信息,向sale表中增加信息 Sale sale = new Sale(null,goodsId,nums); saleDao.insertSale(sale); //更新库存 Goods goods = goodsDao.selectGoods(goodsId); if (goods==null){ //商品不存在 throw new NullPointerException("编号是:"+goodsId+" 商品不存在!"); }else if(goods.getAmount()<nums){ //库存不足 throw new NotEnoughException("编号是:"+goodsId+" 库存不足!"); } System.out.println(); //修改库存 Goods buyGoods = new Goods(); buyGoods.setId(goodsId); buyGoods.setAmount(nums); goodsDao.updateGoods(buyGoods); }
具体spring配置文件
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--声明数据源 DataSource,作用是链接数据库--> <!--读取配文件中数据库中的信息--> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!--set注入 DataSource提供数据库的信息--> <!--<property name="url" value="jdbc:mysql://127.0.0.1:3306/ssm"/> <property name="username" value="root"/> <property name="password" value="123456"/> <property name="maxActive" value="20"/>--> <!--使用配置文件中的数据--> <property name="url" value="${url}"/> <property name="username" value="${user}"/> <property name="password" value="${password}"/> <property name="maxActive" value="${max}"/> </bean> <!--声明mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory的--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--set注入,把数据库连接池付给-dataSource属性--> <property name="dataSource" ref="myDataSource"/> <!--mybatis主配置文件的位置--> <property name="configLocation" value="classpath:mybatis.xml"/> </bean> <!--创建dao对象,使用SqlSession的getMapper(StudentDao.class) MapperScannerConfigurer:在内部调用getMapper()生成每个Dao的代理对象 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--指定SqlSessionFactory对象id--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!--指定包名 包名是dao接口所在的包名。多个包逗号分割 MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行一次getMapper()方法,得到每个接口的到dao对象。 创建好的dao对象放在Spring容器中 --> <property name="basePackage" value="com.lishizhan.dao"/> </bean> <!-- +++++++++++++++++++++++++++以上配置是固定的不需要记忆直接copy+++++++++++++++++++++++++++++++++++++++ --> <!--声明service--> <bean id="buyGoodsServiceImpl" class="com.lishizhan.service.impl.BuyGoodsServiceImpl"> <property name="goodsDao" ref="goodsDao"/> <property name="saleDao" ref="saleDao"/> </bean> <!--声明事务管理器对象:使用 Spring 的事务注解管理事务--> <!--事务:需要告诉spring使用的是那种数据库访问技术 声明事务管理器的实现类: mybatis:DateSourceTransactionManager hibernate:hibernateTransactionManager --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--连接数据库指定数据源--> <property name="dataSource" ref="myDataSource"/> </bean> <!--开启事务注解驱动,告诉spring使用注解管理事务,创建代理对象,transaction-manager代表事务管理器--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
(2)使用 AspectJ 的 AOP 配置管理事务
适合大型项目
使用 XML 配置事务代理的方式的不足是,每个目标类都需要配置事务代理。当目标类
较多,配置文件会变得非常臃肿。
使用 XML 配置顾问方式可以自动为每个符合切入点表达式的类生成事务代理。其用法
很简单,只需将前面代码中关于事务代理的配置删除,再替换为如下内容即可。
实现步骤:
-
maven中加入依赖
<!--spring核心ioc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.5.RELEASE</version> </dependency> <!--aspectJ依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>5.2.5.RELEASE</version> </dependency> <!--spring做事务依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.2.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.5.RELEASE</version> </dependency> <!--mybatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.1</version> </dependency> <!--spring和mybatis集成的依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!--MySQL驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.9</version> </dependency> <!--阿里连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency>
-
声明事务管理器对象
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--连接数据库指定数据源--> <property name="dataSource" ref="myDataSource"/> </bean>
-
声明方法需要的事务类型(配置方法的事务属性【隔离级别、传播行为、超时时间】)
<!--声明事务处理:和源代码完全分离--> <!--1,声明事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="myDataSource"/> </bean> <!--2,声明业务方法它的事务属性(隔离级别、超时时间、转播行为)--> <!--注意是:http://www.springframework.org/schema/tx--> <!--id:表示配置内容 transaction-manager:事务管理器对象的id --> <tx:advice id="myAdvice" transaction-manager="transactionManager" > <!--表示配置事务属性--> <tx:attributes> <!--给具体的方法配置事务属性,method可以有多个,分别给不同的方法设置事务属性 name:1,完整的方法名,不带包和类;2,使用通配符 * 表示任意字符 propagation:传播行为 isolation:隔离级别 rollback-for:指定异常名,异常全限定名 --> <tx:method name="buy" propagation="REQUIRED" isolation="DEFAULT" rollback-for="java.lang.NullPointerException,com.lishizhan.exception.NotEnoughException"/> <!--使用通配符指定许多事务方法--> <tx:method name="add*" propagation="REQUIRES_NEW"/> <tx:method name="modify*" propagation="REQUIRES_NEW"/> <tx:method name="remove*" propagation="REQUIRES_NEW"/> <tx:method name="query*" propagation="REQUIRES_NEW"/> <!--包含可能会遇到的所有方法--> <tx:method name="*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice>
-
配置AOP,指定那些类要创建代理
<!--配置AOP--> <aop:config> <!--配置切入点表达式:指定那些类要使用事务 id:切入点表达式,唯一值 expression:切入点表达式,指定那些类要使用事务,aspectj会创建代理对象 com.crm.service.impl.CrmGoodsServiceImpl com.lishizhan.service.BuyGoodsService com.service.impl.OrderGoodsServiceImpl --> <aop:pointcut id="servicePt" expression="execution(* *..service..*.*(..))"/> <!--配置增强器:关联advice和pointcut advice-ref:通知,上面的myAdvice pointcut-ref:切入点表达式 --> <aop:advisor advice-ref="myAdvice" pointcut-ref="servicePt"/> </aop:config>
包结构,
service中的代码
public class BuyGoodsServiceImpl implements BuyGoodsService {
private GoodsDao goodsDao;
private SaleDao saleDao;
public void setGoodsDao(GoodsDao goodsDao) {
this.goodsDao = goodsDao;
}
public void setSaleDao(SaleDao saleDao) {
this.saleDao = saleDao;
}
@Override
public void buy(Integer goodsId, Integer nums) {
//记录销售订单信息,向sale表中增加信息
Sale sale = new Sale(null,goodsId,nums);
saleDao.insertSale(sale);
//更新库存
Goods goods = goodsDao.selectGoods(goodsId);
if (goods==null){
//商品不存在
throw new NullPointerException("编号是:"+goodsId+" 商品不存在!");
}else if(goods.getAmount()<nums){
//库存不足
throw new NotEnoughException("编号是:"+goodsId+" 库存不足!");
}
System.out.println();
System.out.println();
//修改库存
Goods buyGoods = new Goods();
buyGoods.setId(goodsId);
buyGoods.setAmount(nums);
goodsDao.updateGoods(buyGoods);
}
public void addSale(){}
public void addGoods(){}
public void modifySale(){}
public void modifyGoods(){}
public void removeSale(){}
public void removeGoods(){}
public void querySale(){}
public void queryGoods(){}
}
测试:
@Test
public void buy() {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
BuyGoodsService service = (BuyGoodsService) ac.getBean("buyGoodsServiceImpl");
System.out.println("service是代理:"+service.getClass().getName());
// buyGoodsServiceImpl.buy(1001, 1);
// buyGoodsServiceImpl.buy(10012, 1);
service.buy(1002121, 2);
// buyGoodsServiceImpl.buy(1012, 100000);
}