spring——事物操作

spring——事物操作

事物概念

  1. 什么是事物

    事物是数据库的基本单元,逻辑上一组操作要么成功,如果有一个失败,所有操作都失败

    典型场景:银行转账

    ​ 小明转账100元给玛丽

    ​ 小明少了100元,玛丽多了100元

  2. 事物的四个特性

    原子性

    一致性

    隔离性

    持久性

事物操作(搭建事物操作环境)

  1. Dao:数据库操作,不写业务:创建方法(少钱,多钱)

  2. service:业务操作:创建转账方法,调用Dao里的两个方法

  3. 实现过程

    创建数据库表,user,添加记录

    在这里插入图片描述

    配置文件,编写数据库连接池,在JdbcTemplate注入dataSource数据池

    <?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="src.matter"></context:component-scan>
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost:3306/bookstore"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
        <!--JdbcTemplate对象-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
    </beans>
    

    创建UserDao接口类,并编写方法

    public interface UserDao {
        void increaseMoney();
        void reduceMoney();
    }
    

    编写实现类,并通过注解方式创建对象以及注入JdbcTemplate,实现方法

    @Repository
    public class UserDaoImpl implements UserDao{
        @Autowired
        private JdbcTemplate jdbcTemplate;
        @Override
        public void increaseMoney() {
            String sql="update user set money=money+? where username=?";
            jdbcTemplate.update(sql,"100","Marry");
        }
    
        @Override
        public void reduceMoney() {
            String sql="update user set money=money-? where username=?";
            jdbcTemplate.update(sql,"100","Xiaoming");
        }
    }
    

    编写service类,创建对象,注入属性,实现业务代码

    @Service
    public class UserService {
        @Autowired
        private UserDao userDao;
        public void transferAccount(){
            userDao.increaseMoney();
            userDao.reduceMoney();
        }
    }
    

    测试类

    public class test {
        public static void main(String[] args) {
            ApplicationContext context=new ClassPathXmlApplicationContext("src/matter/bean.xml");
            UserService userService=context.getBean("userService",UserService.class);
            userService.transferAccount();
        }
    }
    

    运行结果

    在这里插入图片描述

  4. 正常执行,没有问题,异常场景,转账者出现异常(突然断电)

    解决方案:事物操作

    事物操作过程

    • 开启事物
    • 进行业务操作
    • 没有发生异常,提交事物
    • 出现异常,事物回滚

spring事物管理介绍

  1. 事物添加到JavaEE三层结构里的service层

  2. 在spring进行事物管理操作

    有两种方式:编程式事物管理和声明式事务管理(常用)

  3. 声明式事物管理

    基于注解方式(常用)

    基于xml配置文件

  4. 在spring配置文件中进行声明式事务管理,底层使用AOP原理

  5. spring事物管理API

    提供一个接口代理事物管理器,接口针对不同的框架提供不同的实现类

基于注解声明式事务管理

  1. 在spring配置文件中配置事物管理器(创建实现类的对象)

    <!--配置事物管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
  2. 在spring配置文件中开启事物注解

    引入命名空间tx

    <?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">
    

    开启事物注解

    <!--开启事物注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
    
  3. 在service类上面或者需要添加事物的方法的上面添加事物注解@Transactional

    加在类上面:这个类里的方法都进行事物管理

    加载方法上面:仅该方法进行事物管理

    @Service
    public class UserService {
        @Autowired
        private UserDao userDao;
        @Transactional
        public void transferAccount(){
            userDao.reduceMoney();
            int i=66/0;//模拟异常
            userDao.increaseMoney();
        }
    }
    

声明式事务管理的参数配置

  1. propagation:事物传播行为,当一个事物方法被另一个事物方法调用时称为事物传播行为

    REQUIED:如果有事物在运行,当前的方法就在这个事物内运行,否则就启动一个新的事物,并在自己的事物内运行

    REQUIRED_NEW:当前的方法必须启动新事物,并在自己的事物内运行,如果有事物正在运行,应该将它挂起

    SUPPORTS:如果有事物在运行,当前的方法就在这个事物内运行,否则可以不运行在事务中。

  2. isolation:事物隔离性

    事物特性——隔离性:多事物操作之间不会产生影响,不考虑隔离性会产生很多问题

    产生的问题:脏读、不可重复读、虚读

    脏读:一个未提交的事物读取到另一未提交事物的数据

    不可重复读:一个未提交事物读取到另一提交事物修改数据

    虚读:一个未提交事物读取到另一提交事物增加数据

    解决方法:通过设置隔离级别

    参数脏读不可重复读虚读
    READ UNCOMMITTED×××
    READ COMMITTED××
    REPEATABLE READ×
    SERIALIZABLE
  3. timeout:超时时间

    事物需要在一定时间内进行提交,如果不提交就进行回滚

    默认值为-1,设置时间以秒为单位

  4. readOnly:是否只读

    读:查询操作,写:增删改操作

    默认值为false,两个值:true false

  5. rollbackFor:回滚

    设置查询哪些异常进行事物回滚

  6. noRollbackFor:不回滚

    设置查询哪些异常不进行事物回滚

    @Transactional(propagation = ,isolation = ,timeout = ,readOnly = true,rollbackFor = ,noRollbackFor = )
    

基于xml配置实现声明式事务管理

  1. 在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" 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.xsd
                                http://www.springframework.org/schema/tx  http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
        <!--开启组件扫面-->
        <context:component-scan base-package="src.matter"></context:component-scan>
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost:3306/bookstore"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
        <!--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:advice id="advice">
            <tx:attributes>
                <tx:method name="transferAccount"/>
            </tx:attributes>
        </tx:advice>
        <!--配置切入点和切面-->
        <aop:config>
            <aop:pointcut id="pointcut" expression="execution(* src.matter.service.UserService.*(..))"/>
            <aop:advisor advice-ref="advice" pointcut-ref="pointcut"></aop:advisor>
        </aop:config>
    </beans>
    

完全注解声明式事务管理

  1. 创建配置类代替xml文件

    声明配置类

    开启组件扫描

    开启事务

    创建数据库连接池

    创建JdbcTemplate对象

    创建事务管理器对象

@Configuration
@ComponentScan(basePackages = "src.matter")
@EnableTransactionManagement
public class config {
    //创建数据库连接池
    @Bean
    public DruidDataSource getDataSource(){
        DruidDataSource druidDataSource=new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/bookstore");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("root");
        return druidDataSource;
    }
    //创建JdbcTemplate
    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate=new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }
    //事物管理器
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}

mplate;
}
//事物管理器
@Bean
public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){
DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rush006

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值