Spring-事物操作学习

事务概念

1、什么是事务
(1)事务是数据库操作最基本的单元,逻辑上的一组操作,要么都成功,如果有一个失败都失败。
(2)典型场景:银行转账
lucy转账100给mary
lucy少100,mary多100
如果转账期间有问题,就都不会改变

2、事务特性(ACID)
(1)原子性:不可分割,要成功要失败都一起
(2)一致性:操作前和操作后总量不变
(3)隔离性:多事务操作互不影响
(4)持久性:数据持续变化

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

在这里插入图片描述
1、创建数据库表,添加数据

在这里插入图片描述
2、创建service,搭建dao完成对象创建和注入
(1)service里注入dao,在dao注入jdbcTemplate,在jdbcTemplate中注入dataSource

@Service
public class UserService {

    //注入dao
    @Autowired
    private UserDao userDao;
}
@Repository
public class UserDaoIm implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/aop   http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--开启组件扫描-->
    <context:component-scan base-package="com.spring5"/>
    <!--德鲁伊数据库连接池配置-->
    <bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="jdbc:mysql:///user_db"/>
        <property name="username" value="root"/>
        <property name="password" value="admin"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>

    </bean>

    <!--创建jdbcTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource"  ref="dateSource"></property>
    </bean>
</beans>

3、在dao创建两个方法,多钱和少钱方法,在service创建方法(转账的方法)

    @Override
    public void addMoney() {
        String sql="update t_acount set money=money+? where username=?";
        jdbcTemplate.update(sql,100,"mary");
    }

    @Override
    public void reduceMoney() {
    String sql="update t_acount set money=money-? where username=?";
    jdbcTemplate.update(sql,100,"lucy");
    }

@Service
public class UserService {

    //注入dao
    @Autowired
    private UserDao userDao;

    //转账的方法
    public void accountMoney()
    {
        userDao.reduceMoney();
        userDao.addMoney();
    }
}

测试:

    @Test
    public void TestAccount1()
    {
        ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService=context.getBean("userService", UserService.class);
        userService.accountMoney();
    }

上面代码正常执行没问题,如果代码出现异常,就会有问题

    //转账的方法
    public void accountMoney()
    {
        userDao.reduceMoney();
        int i=10/0;
        userDao.addMoney();
    }

这种效果是不对的,解决方案就是用事务

事务操作过程:

@Service
public class UserService {

    //注入dao
    @Autowired
    private UserDao userDao;

    //转账的方法
    public void accountMoney()
    {
        try {
            //第一步开启事务

            //进行业务操作
            userDao.reduceMoney();
            int i=10/0;
            userDao.addMoney();

            //第三步,没有发生异常,提交事务
        }catch (Exception e)
        {
            //第四步:出现异常,事务回滚
            e.printStackTrace();
        }

    }
}

事务操作(Spring事务管理介绍)

1、事务添加JavaEE三层结构的Service层(业务逻辑层)
2、在Spring里进行事务管理操作
(1)	编程式事务管理(如上例)和声明式事务管理(使用)
3、声明式事务管理
(1)基于注解方式(最方便)
(2)基于XML配置文件方式

4、Spring进行声明事务管理,底层使用AOP原理
5、Spring事务管理API
(1)提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200821065232670.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1N1bk5pZ2h0eg==,size_16,color_FFFFFF,t_70#pic_center)

事务操作(注解声明式)

1、在Spring配置文件中配置事务管理器

    <!--创建事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dateSource"></property>
    </bean>

2、在Spring配置文件 ,开启事务注解
(1)在Spring配置文件中引入名称空间tx

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/aop   http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/tx    http://www.springframework.org/schema/tx/spring-tx.xsd">

(2)开启事务注解

    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

3、在service类上面(获取service类里面方法上面)添加事务注解
(1)@Transactional,这个注解添加到类上面,也可方法上面
(2)如果在类上面,那类下面的方法都添加了注解
(3)如果添加到方法上面,那就是在这个方法添加注解


@Service
@Transactional
public class UserService {

    //注入dao
    @Autowired
    private UserDao userDao;

事务管理(声明式事务管理参数配置)

1、在Service类上面添加注解@Transactional,可以配置事务相关参数
在这里插入图片描述
2、propagation:事务传播行为
(1)多事务方法直接进行调用,这个事务过程中 是如何进行管理的
一个有事务方法调无事务方法:
在这里插入图片描述
或者两个方法都有事务怎么操作
其他传播行为:
在这里插入图片描述
在这里插入图片描述

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class UserService {

3、ioslation:事务隔离级别
(1)事务有个特性隔离性,多事务操作之间不会产生影响。不考虑隔离性会有很多问题。
(2)有三个读的问题:脏读、不可重复读、虚(幻)读
脏读:一个未提交的事务读取到另一个未提交的数据
在这里插入图片描述
当事务回滚时,左边读取到数据就会有问题。

不可重复读:一个未提交的数据读取到了另一个提交事务修改数据
在这里插入图片描述
虚度:一个未提交的数据读取到了另一个提交事务添加 数据

(3)解决:通过设置事务的隔离性,解决读问题
在这里插入图片描述

@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.SERIALIZABLE)

mysql默认是可重复读级别

4、timeout:超时时间
(1)事务需要在一定的时间内进行提交,如果不提交则回滚
(2)默认值-1,设置以秒为单位

@Transactional(timeout = 5,propagation = Propagation.REQUIRED,isolation = Isolation.SERIALIZABLE)

5、timeOnly:是否只读
(1)读:查询操作,写:添加修改删除操作
(2)readOnly默认值false,表示可以读写
(3)设置为true,只能做查询操作

@Transactional(readOnly = true,timeout = 5,propagation = Propagation.REQUIRED,isolation = Isolation.SERIALIZABLE)

6、rollbackFor:回滚
(1)设置出现哪些异常进行事务回滚

7、noRollbackFor:不回滚
(1)设置出现哪些异常不进行事务回滚

事务管理(XML声明式事务管理)

1、在Spring配置文件中进行配置
第一步:配置事务管理器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/aop   http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/tx    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--开启组件扫描-->
    <context:component-scan base-package="com.spring5"/>
    <!--德鲁伊数据库连接池配置-->
    <bean id="dateSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="jdbc:mysql:///user_db"/>
        <property name="username" value="root"/>
        <property name="password" value="admin"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>

    </bean>

    <!--创建jdbcTemplate对象-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource"  ref="dateSource"></property>
    </bean>

    <!--创建事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dateSource"></property>
    </bean>

第二步:配置通知

   <!--配置通知-->

    <tx:advice id="txadvice">
        <!--配置事务参数-->
        <tx:attributes>
            <!--指定哪种规则的方法上面添加事务-->
            <tx:method name="accountMoney" propagation="REQUIRED"/>
<!--            <tx:method name="account*"/>-->
        </tx:attributes>

    </tx:advice>

第三步:配置切入点和切面

    <!--配置切入点和切面-->
    <aop:config>
        <!--配置切入点-->
        <aop:pointcut id="pt" expression="execution(* com.spring5.service.UserService.*(..))"/>
        <!--配置切面-->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
    </aop:config>

事务管理(完全注解声明式事务管理【多用springboot】)

1、创建配置类,使用配置类替代xml配置文件

package com.spring5.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import javax.swing.*;

@Configuration
@ComponentScan(basePackages = "com.spring5") //开启组件扫描
@EnableTransactionManagement //开启事务
public class TxConfig {
    //创建数据库连接池
    @Bean
    public DruidDataSource getDruidDateSource()
    {
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///user_db");
        dataSource.setUsername("root");
        dataSource.setPassword("admin");
        return dataSource;
        }

    //创建jdbc对象
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource)
    {

        JdbcTemplate jdbcTemplate=new JdbcTemplate();
        //注入dateSource
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //创建事务管理器对象
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource)
    {
        DataSourceTransactionManager dataSourceTransactionManager=new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值