【Spring进阶系列丨最终篇】一文详解Spring中的事务控制

这篇具有很好参考价值的文章主要介绍了【Spring进阶系列丨最终篇】一文详解Spring中的事务控制。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

0、说明

本篇文章是【Spring进阶系列】专栏的最后一篇文章,至此,我们对Spring的学习就告一段落,接下来我会持续更新【Spring+SpringMVC+MyBatis整合】专栏,欢迎免费订阅!

【Spring进阶系列丨最终篇】一文详解Spring中的事务控制,Spring进阶系列,spring,数据库,java,spring boot,学习

一、Spring事务控制

【Spring进阶系列丨最终篇】一文详解Spring中的事务控制,Spring进阶系列,spring,数据库,java,spring boot,学习

  • 事务需要放在业务层(service)
  • Spring的事务是基于AOP的
  • Spring的事务控制有两种:编程式事务【了解】和声明式事务【重点】
  • 声明式事务分为:基于xml配置和基于注解配置

1、事务的环境准备

1.1、导入依赖

<dependencies>

        <!-- 导入Spring的jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>

        <!-- 添加对AOP的支持  -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!-- 事务的jar包    -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>

        <!-- 数据库驱动  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
  	
  		<!-- 操作数据库的支持	-->
  		<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>

        <!--  单元测试框架  -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
</dependencies>

1.2、添加AOP的约束

<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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>

1.3、数据库准备

create database bank;

use bank;

create table t_account(
	id int primary key auto_increment,
  	name varchar(30),
  	balance int
);

insert into t_account(name,balance) values('段康家',2000);
insert into t_account(name,balance) values('彭依凝',2000);

1.4、定义Bean

// 定义实体
public class Account {
    
    private Integer id;
    
    private String name;
    
    private Integer balance;
}
// 业务接口
public interface AccountService {

    public void transfer(Integer srcId,Integer destId,Integer money);

}
public class AccountServiceImpl implements AccountService {

    @Override
    public void transfer(Integer srcId, Integer destId, Integer money) {
        // 源账号
        Account srcAccount = accountDao.selectById(srcId);
        Integer srcBalance = srcAccount.getBalance();
        srcAccount.setBalance(srcBalance - money);
        
        accountDao.updateById(srcAccount);
        
        // 目标账号
        Account destAccount = accountDao.selectById(destId);
        Integer destBalance = destAccount.getBalance();
        destAccount.setBalance(destBalance + money);
        
        accountDao.updateById(destAccount);
    }
}
// dao接口
public interface AccountDao {
    
    public Account selectById(Integer id);
    
    public void updateById(Account account);
    
}
// dao实现类
public class AccountDaoImpl implements AccountDao {
    @Override
    public Account selectById(Integer id) {

        String sql = "select id,name,balance from t_account where id = ?";

        List<Account> accounts = getJdbcTemplate().query(sql,new BeanPropertyRowMapper<Account>(Account.class),id);

        return accounts.get(0);
    }

    @Override
    public void updateById(Account account) {

        String sql = "update t_account set balance = ? where id = ?";

        getJdbcTemplate().update(sql,account.getBalance(),account.getId());
    }
}

1.5、主配置文件定义

<beans> 
	<!-- 配置Dao层-->
    <bean id="accountDao" class="cn.bdqn.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref=""/>
    </bean>

    <!-- 配置业务层-->
    <bean id="accountService" class="cn.bdqn.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!-- 配置数据源  -->
    <bean id="dataSource" 																class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql:///bank"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

</beans>

1.6、测试

@Test
public void testTransfer() throws Exception{

        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        AccountService accountService = (AccountService) ac.getBean("accountService");
        accountService.transfer(1,2,100);
}

2、基于xml的声明式事务

2.1、配置事务管理器

<!--  1、配置事务管理器  -->
<bean id="transactionManager" 																																		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
</bean>

2.2、配置事务的通知

 <!-- 2、配置事务的通知  -->
<tx:advice id="txAdvice" transaction-manager="transactionManager"/>

2.3、配置AOP

​ 重点是配置切入点表达式及事务通知和切入点表达式的关系

<!-- 3、开启配置AOP 配置切入点表达式及事务通知和切入点表达式的关系-->
<aop:config>
        <aop:pointcut id="pt" expression="execution(* cn.bdqn.service.impl.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"/>
</aop:config>

2.4、配置事务的属性

​ 注意:事务的属性在tx:advice标签的内部。

isolation:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。

propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。

read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。

timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。

rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚。

no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。

<!-- 2、配置事务的通知  -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
   <!-- 配置事务的属性-->
   <tx:attributes>
        <tx:method name="transfer" isolation="DEFAULT" propagation="REQUIRED" 
                   read-only="false"/>
   </tx:attributes>
</tx:advice>

3、基于注解的声明式事务

3.1、配置事务管理器

<!--  1、配置事务管理器  -->
<bean id="transactionManager" 																																				class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
</bean>

3.2、在业务类添加注解

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

3.3、配置JdbcTemplate模板

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

3.4、在Dao类添加注解

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;
}

3.5、配置类中扫描包

<context:component-scan base-package="cn.bdqn"/>

3.6、开启spring对注解事务的支持

<tx:annotation-driven transaction-manager="transactionManager"/>

3.7、在业务层@Transactional注解

@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;
}

3.8、测试

@Test
public void testTransfer() throws Exception{

        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        AccountService accountService = (AccountService) ac.getBean("accountService");
        accountService.transfer(1,2,100);
}


【Spring进阶系列丨最终篇】一文详解Spring中的事务控制,Spring进阶系列,spring,数据库,java,spring boot,学习文章来源地址https://www.toymoban.com/news/detail-858096.html

到了这里,关于【Spring进阶系列丨最终篇】一文详解Spring中的事务控制的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Spring Boot系列】- Spring Boot事务应用详解

    事务(Transaction)是数据库操作最基本单元,逻辑上一组操作,要么都成功。如果有一个操作失败。则事务操作都失败(回滚(Rollback))。 事务的四个特性(ACID): 1. 原子性(Atomicity) 一个事务(Transaction)中的所有操作,要么全部完成,要么全部不完成,不会结束在中间

    2024年02月08日
    浏览(38)
  • 【Spring全家桶系列】Spring中的事务管理(基于注解完成实现)

    ⭐️ 前面的话 ⭐️ 本文已经收录到《Spring框架全家桶系列》专栏,本文将介绍Spring中的事务管理,事务的概念与作用,以及Spring事务的属性和传播机制。 📒博客主页:未见花闻的博客主页 🎉欢迎关注🔎点赞👍收藏⭐️留言📝 📌本文由 未见花闻 原创, CSDN 首发! 📆首

    2024年02月07日
    浏览(35)
  • 【Spring进阶系列丨第七篇】Spring框架新注解分类及详解

    1.1.1、定义一个类 1.1.2、使用Configuration注解修饰类 1.1.3、作用 ​ 使用Configuration注解修饰的类表示的是:当前类是一个配置类。该类的作用和beans.xml是一样的,换句话说,该 注解所修饰的类就是用来代替beans.xml文件的。 1.2.1、定义bean 1.2.2、在主配置类中注册bean ​ 在以前,

    2024年04月10日
    浏览(85)
  • 【Spring进阶系列丨第四篇】学习Spring中的Bean管理(基于xml配置)

    在之前的学习中我们知道,容器是一个空间的概念,一般理解为可盛放物体的地方。在Spring容器通常理解为BeanFactory或者ApplicationContext。我们知道spring的IOC容器能够帮我们创建对象,对象交给spring管理之后我们就不用手动去new对象。 那么Spring是如何管理Bean的呢? 简而言之,

    2024年02月05日
    浏览(59)
  • 【Spring进阶系列丨第八篇】Spring整合junit & 面向切面编程(AOP)详解

    ​ @ContextConfiguration注解需要注意的细节是: classes:指定的是主配置类的字节码 locations:指定xml文件的位置 ​ 首先来看一个问题,假如我现在有一个UserServiceImpl用户业务类,其中呢,有一个保存用户的方法,即: ​ 现在的需求是:我要在保存用户之前新增事务的功能,你

    2024年04月13日
    浏览(43)
  • Spring系列篇--关于IOC【控制反转】的详解

    接下来看看由辉辉所写的关于Spring的相关操作吧 目录 🥳🥳Welcome Huihui\\\'s Code World ! !🥳🥳  一.什么是Spring 二.Spring的特点 三.什么是IOC 场景模拟: 控制反转: 使用步骤 1 创建Maven的war项目然后配置web的相关依赖以及项目结构的配置 2在pom.xml文件中配置Spring的依赖 3 在resourc

    2024年02月12日
    浏览(38)
  • 【Spring进阶系列丨第十篇】基于注解的面向切面编程(AOP)详解

    ​ 注意,该类的两个细节: a、@Component注解向容器中注册一个Bean。 b、@Aspect注解表示这个是一个切面类。 c、@Before注解表示的是这个是前置增强/前置通知。 ​ 注意:对于业务Bean,我们也需要通过@Service注解来向容器中注册。 ​ 问题:我们看到对于切面类中定义的通知,有

    2024年04月23日
    浏览(39)
  • 【Spring进阶系列丨第九篇】基于XML的面向切面编程(AOP)详解

    1.1.1、beans.xml中添加aop的约束 1.1.2、定义Bean ​ 问题:我们上面的案例经过测试发现确实在调用业务方法之前增加了日志功能,但是问题是仅仅能针对某一个业务方法进行增强,而我们的业务方法又有可能有很多,所以显然一个一个的去配置很麻烦,如何更加灵活的去配置呢

    2024年04月18日
    浏览(42)
  • 【JavaEE进阶】Spring事务和事务传播机制

    Spring 事务是 Spring 框架提供的一种机制,用于 管理数据库操作或其他资源的一组相关操作 ,以确保它们在一个原子、一致、可靠和隔离的执行单元内进行。事务用于维护数据的完整性并支持并发访问数据库时的数据一致性。 Spring 事务的主要特点包括: 原子性(Atomicity):

    2024年02月09日
    浏览(54)
  • 【MySQL】一文搞懂 MySQL 中的事务

    谈事务,一般就是说数据库事务。本篇文章以 MySQL 为例谈一谈事务。 MySQL 的 Indndb 引擎和 bdb 引擎支持事务。MySQL 的myisam ,memory 等存储引擎是不支持事务的。 事务是逻辑上的一组操作,要么都执行,要么都不执行。 事务具体四大特性,也就是经常说的 ACID ,常用的MySQL、Sq

    2024年02月09日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包