spring 实现事务

1、什么是事务

小胡通过银行给小赵转账100元,在正常情况下,小胡的银行卡余额会减少100元,小赵的账号会增加100元。在转账过程中出现问题,如银行数据库突然崩了,导致转账失败,我们需要确保所有数据回滚到转账之前。也就是说转账失败,小胡的账号余额不能减少,小赵的余额也不能增加。

2、事务的4个特性(ACID)

原子性(Atomic):原子性确保所有操作要么全部实现,要么全部失败。如果所有的操作成功了,事务也就成功了,如果存在某个事件失败,事务会回滚,所有数据会回到事务开始之前的状态。

一致性(Consistent):无论事务成功还是失败,保持数据一致

隔离性(Isolated):事务允许多个用户同时操作同一个数据,但每个用户对数据的操作是互相不影响的。所以事务需要隔离每个用户操作,避免发生同步读写数据的操作

持久性(Durable):事务完成,数据进行持久化操作,通常写入数据库中

3、事务分类

声明式事务:通过代码手动提交回滚的事务控制方法

编程式事务:通过xml文件或者注解实现自动回滚事务

4、声明式事务属性

1、传播行为

定义了客户端与被调用的方法之间的事务边界。spring规定了7种传播行为。

2、隔离级别

隔离级别定义了一个事务能被其他事务影响的级别。可能会出现的问题。

脏读:当前事务读取了其他事务改写但还未提交的数据。导致读取的数据是无效。

不可重复读:多次读取数据,但前后数据不同。

幻读:和不可重复读相似,当前事务读取了一段数据,还未读取完,其他输入插入了一些新数据,当前数据就读取了一些之气没有的数据。

3、只读

设置当前事务是否为只读

4、事务超时

设置事务运行时间。

5、回滚规则

设置回滚规则,在哪些情况下可以回滚。

5、使用注解配置声明式事务

1、导入依赖

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.15.RELEASE</version>
    </dependency>
    <!--切面依赖-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.13</version>
    </dependency>
    <!--AOP-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.2.15.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>javax.annotation-api</artifactId>
      <version>1.3.1</version>
    </dependency>
    <!--mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.25</version>
    </dependency>
    <!--数据库连接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.21</version>
    </dependency>
    <!--DataSource-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.15.RELEASE</version>
    </dependency>
  </dependencies>

2、创建StudentDao 接口

public interface StudentDao {
    public int insertStudent();
    public int insertStudentInfo();
}

3、创建接口实现类

@Repository:创建数据访问层Bean

@Repository
public class StudentDaoImpl implements StudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insertStudent() {
        String sql="insert into student values(null,?,?,?)";
        Object[] all = {"qwe","2022-9-1",90};
        int update = jdbcTemplate.update(sql, all);
        return update;
    }

    @Override
    public int insertStudentInfo() {
        String sql="update student set s_sc = s_sc + ? where s_id = ?";
        Object[] all = {1,11};
        int update = jdbcTemplate.update(sql, all);
        return update;
    }
}

4、创建service层

一般都将事务注解@Transactional夹在service层。因为service完成的是一个服务,会多次调用多个dao层。

@Service
@Transactional
public class StudentService {

    @Autowired
    private StudentDao student;

    public void makePlay(){
        System.out.println(student.insertStudentInfo());
        System.out.println("------------------------");
        int a=1/0;
        System.out.println(student.insertStudent());
    }
}

5、创建jdbc.properties

jdbc.Driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/stu?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
jdbc.username=root
jdbc.password=root

6、applicationContext配置文件

<?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:aop="http://www.springframework.org/schema/aop"
       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/aop
           https://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="Transactional"/>

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

    <!--导入jdbc.properties-->
    <context:property-placeholder location="jdbc.properties"/>

    <!--配置druid数据库连接-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.Driver}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--jdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--配置事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据库连接池-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

</beans>

7、测试

public static void main(String[] args) throws SQLException, UnsupportedEncodingException {
    ApplicationContext context = new     
              ClassPathXmlApplicationContext("applicationContext.xml");
    StudentService student = (StudentService) context.getBean("studentService");
    student.makePlay();
}

6、使用xml配置事物

使用xml配置事物,是基于AOP实现的,所以需要配置AOP。

1、创建接口

public interface StudentDao {
    public int insertStudent();
    public int insertStudentInfo();
}

2、创建接口实现类

在applicationContext.xml配置bean

public class StudentDaoImpl implements StudentDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insertStudent() {
        String sql="insert into student values(null,?,?,?)";
        Object[] all = {"qwe","2022-9-1",90};
        int update = jdbcTemplate.update(sql, all);
        return update;
    }

    @Override
    public int insertStudentInfo() {
        String sql="update student set s_sc = s_sc + ? where s_id = ?";
        Object[] all = {1,11};
        int update = jdbcTemplate.update(sql, all);
        return update;
    }
}

3、创建service层

在applicationContext.xml配置bean

public class StudentService {

    @Autowired
    private StudentDao student;

    public void makePlay(){
        System.out.println(student.insertStudentInfo());
        System.out.println("------------------------");
        int a=1/0;
        System.out.println(student.insertStudent());
    }
}

4、applicationContext.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:aop="http://www.springframework.org/schema/aop"
       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/aop
           https://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="Transactional"/>

    <!--配置AOP注解-->
    <aop:aspectj-autoproxy/>

    <!--配置 bean-->
    <bean id="studentDao" class="Transactional.SQL.dao.impl.StudentDaoImpl"/>
    <bean id="studentService" class="Transactional.SQL.service.StudentService"/>

    <!--导入jdbc.properties-->
    <context:property-placeholder location="jdbc.properties"/>

    <!--配置druid数据库连接-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.Driver}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

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

    <!--配置事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据库连接池-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--配置事务通知-->
    <tx:advice id="txManager" transaction-manager="transactionManager">
        <!--配置事务属性-->
        <tx:attributes>
            <!--service层方法-->
            <tx:method name="makePlay"/>
        </tx:attributes>
    </tx:advice>

    <!--AOP切面,配置拦截方法-->
    <aop:config>
        <!--execute指向makePlay-->
        <aop:pointcut id="txcut" expression="execution(*         
         Transactional.SQL.service.StudentService.*(..))"/>
       
        <!--匹配 tx:advice -->
        <aop:advisor advice-ref="txManager" pointcut-ref="txcut"/>
    </aop:config>
</beans>

5、配置jdbc.properties文件

6、测试

public static void main(String[] args) throws SQLException, UnsupportedEncodingException {
    ApplicationContext context = new 
        ClassPathXmlApplicationContext("applicationContext.xml");
    StudentService student = (StudentService) context.getBean("studentService");
    student.makePlay();
}

7、数据库结构

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值