Spring的声明式事务控制

Spring中的声明式事务控制(配置方式)

一.关于Spring中的事务控制

第一:JavaEE 体系进行分层开发,事务处理位于业务层,Spring 提供了分层设计业务层的事务处理解决方案。
第二:spring 框架为我们提供了一组事务控制的接口。这组接口是在spring-tx-5.0.2.RELEASE.jar 中。
第三:spring 的事务控制都是基于 AOP 的,它既可以使用编程的方式实现,也可以使用配置的方式实现。

二.两种方式实现事务控制案例

①基于xml的声明式事务控制

1.导入jar包
<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.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.6</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.3.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.2</version>
            <scope>compile</scope>
        </dependency>
2.创建bean.xml文件

配置可以分为六步:
1.配置事务管理器
2.配置事物的通知
id:给事务通知起一个唯一的标识
transaction-Manager:给事务通知提供一个事务管理器引用
3.配置aop
4.配置切入点表达式
5.建立切入点表达式和事务通知的对应关系
6.配置事务的属性
isolation=:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。
propagation=指定事务的传播行为。
read-only:是否是只读事务。默认 false,不只读。
rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。
没有默认值,任何异常都回滚。
no-rollback-for=:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回
滚。没有默认值,任何异常都回滚。
timeout=用于z指定事务的超时时间,默认是-1,表示永不超时,如果指定了时间,以秒为单位

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      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
       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="com.xszx"/>
   <!--引入外部配置文件-->
   <context:property-placeholder location="db.properties"/>

   <bean id="teacherDao" class="com.xszx.dao.TeacherDao">
   <!-- 注入datasource-->
       <property name="dataSource" ref="dataSource"/>
   </bean>
   <!--<bean id="teacherService" class="com.xszx.service.TeacherService">
       <property name="teacherDao" ref="teacherDao"></property>
   </bean>-->
   <!--配置数据源-->
   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
       <property name="driverClassName" value="${jdbc.driverClassName}"/>
       <property name="url" value="${jdbc.url}"/>
       <property name="username" value="${jdbc.username}"/>
       <property name="password" value="${jdbc.password}"/>
   </bean>
<!--    Spring中基于xml的声明式事务控制-->
   <!--1.配置事务管理器-->
   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <property name="dataSource" ref="dataSource"/>
   </bean>
   <!--2.配置事物的通知
           id:给事务通知起一个唯一的标识
           transaction-Manager:给事务通知提供一个事务管理器引用
           -->
   <tx:advice id="txAdvice" transaction-manager="transactionManager">
           <!--6.配置事务的属性-->
   <tx:attributes>
       <tx:method name="remove" propagation="REQUIRED" read-only="false" />
       <tx:method name="find*" propagation="SUPPORTS" read-only="true"/><!-- 查询方法的规范写法-->
   </tx:attributes>
</tx:advice>
   <!--3.配置aop-->
   <aop:config>
   <!-- 4.配置切入点表达式-->
       <aop:pointcut id="pt1" expression="execution(* com.xszx.service.*.*(..))"/>
   <!--5. 建立切入点表达式和事务通知的对应关系-->
       <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
   </aop:config>


</beans>
3.dao层代码

import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;


/**
 * @author Mr Z
 * @create 2020 12 2020/12/15 20:21
 */
@Repository
public class TeacherDao extends JdbcDaoSupport {

    public int delete(int tno){
        String sql="delete from teacher where tno=?";
        int rows=this.getJdbcTemplate().update(sql,tno);
        return rows;
    }
}
4.业务层代码
import com.xszx.dao.TeacherDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Mr Z
 * @create 2020 12 2020/12/15 20:22
 */
@Service
public class TeacherService {
    @Autowired
    private TeacherDao teacherDao;
    @Transactional(propagation = Propagation.REQUIRED)
    public int remove(int tno){
        System.out.println("TeacherService.remove");
        //int a=1/0;
        int delete = teacherDao.delete(tno);
        return delete;
    }
}
5.业务层代码
import com.xszx.service.TeacherService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author Mr Z
 * @create 2020 12 2020/12/16 15:25
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class ServiceTest {
    @Autowired
     private  TeacherService teacherService;
    @Test
    public  void deleteTest(){
        int remove = teacherService.remove(10);
        System.out.println("remove = " + remove);
    }
    
}

②基于注解的声明式事务控制

1.导入jar包同上
2.配置数据库属性集(mysql 8)
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sims?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
3.Jdbc 配置类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;

/**
 * @author Mr Z
 * @create 2021 01 2021/1/8 13:09
 */
public class JdbcConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    /**
     * 创建JdbcTemplate
     * @param dataSource
     * @return
     */
    @Bean(name = "jdbcTemplate")
    private JdbcTemplate createJdbcTemplate(DataSource dataSource){
        return  new JdbcTemplate(dataSource);
    }

    /**
     * 创建数据源对象
     * @return
     */
    @Bean(name = "dataSource")
    public DataSource createDateSource(){
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
}
4.TransactionManager类
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * @author Mr Z
 * @create 2021 01 2021/1/8 13:26
 */

public class TransactionManager {
    @Bean(name ="transactionManager" )
    public PlatformTransactionManager createTransactionManager(DataSource dataSource){
        return  new DataSourceTransactionManager(dataSource);
    }
}
5.将各项配置导入spring配置类中
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;

import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author Mr Z
 * @create 2021 01 2021/1/8 12:37
 */
@Configuration
@ComponentScan("com.xszx")
@Import({JdbcConfig.class,TransactionManager.class})
@PropertySource("db.properties")
@EnableTransactionManagement
public class SpringConfiguration {
}
6.Dao层和业务层同上,注:业务层与xml配置方式不同点在于

@ContextConfiguration(classes= SpringConfiguration.class)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值