事务操作-Spring声明式事务管理(注解方式)

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

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

2.在Spring配置文件,开启事务注解

  (1)在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: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 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"></tx:annotation-driven>

  (3)在service类上面(或者service类里面方法上面)添加事务注解

    1.@Transactional,这个注解添加到类上面,也可以添加在方法上面

    2.如果把这个注解添加到类上面,这个类里面的所有方法都添加事务

    3.如果把这个注解添加到类里面的方法上面,这个方法添加事务

posted @ 2021-12-03 10:51  Soleili  阅读(194)  评论(0编辑  收藏  举报