首页 > 其他分享 >【Spring】事务管理

【Spring】事务管理

时间:2023-04-10 09:22:43浏览次数:30  
标签:事务管理 AccountDao applicationContext Spring jdbcTemplate money public String

添加Maven依赖:

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.6</version>
      <scope>runtime</scope>    
    </dependency>
    <dependency>
      <groupId>aopalliance</groupId>
      <artifactId>aopalliance</artifactId>
      <version>1.0</version>    
    </dependency>

实体类Account.java

一、基于配置

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: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/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 注册bean -->
    <bean name="userDao" class="com.xiaobiti.dao.impl.UserDaoImpl"/>
    <bean name="xmlAdvice" class="com.xiaobiti.demo.xmlAdvice"/>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 数据库驱动 -->
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <!-- 连接数据库url -->
        <property name="url" value="jdbc:mysql://localhost/spring?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai" />
        <property name="username" value="root"/><!-- 连接数据库用户名 -->
        <property name="password" value="1234"/><!-- 连接数据库密码 -->
    </bean>
    <!-- 配置jdbc模板 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 默认必须使用数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 注册bean -->
    <bean id="accountDao" class="com.xiaobiti.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <!--开启自动代理支持-->
    <aop:aspectj-autoproxy/>

    <!-- 4.事务管理器,依赖于数据源 -->
    <bean id="transactionManager" class= "org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" /></bean>

    <!-- 5.编写通知,需要编写对切入点和具体执行事务细节-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED"
                       isolation="DEFAULT" read-only="false" /></tx:attributes>
    </tx:advice>
    <!-- 6.编写aop,使用AspectJ的表达式,让spring自动对目标生成代理-->
    <aop:config>
        <aop:pointcut expression="execution(* com.itheima.*.*(..))"
                      id="txPointCut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

 

 

 AccountDao.java

package com.xiaobiti.dao;

public interface AccountDao {
    public void transfer(String outUser,String inUser,Double money);
}

AccountDaoImpl.java

package com.xiaobiti.dao.impl;

import com.xiaobiti.dao.AccountDao;
import org.springframework.jdbc.core.JdbcTemplate;

public class AccountDaoImpl implements AccountDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // 转账 inUser:收款人; outUser:汇款人; money:收款金额
    public void transfer(String outUser, String inUser, Double money) {
        // 收款时,收款用户的余额=现有余额+所汇金额
        this.jdbcTemplate.update("update account set balance = balance + ? "
                + "where name = ?",money, inUser);
        // 模拟系统运行时的突发性问题
        //int i = 1/0;
        // 汇款时,汇款用户的余额=现有余额-所汇金额
        this.jdbcTemplate.update("update account set balance = balance - ?"
                + "where name = ?",money, outUser);
    }
}

测试运行代码:

public static void main(String[] args) {
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        // 获取AccountDao实例
        AccountDao accountDao =
                (AccountDao)applicationContext.getBean("accountDao");
        // 调用实例中的转账方法
        accountDao.transfer("李四", "张三", 100.0);
        // 输出提示信息
        System.out.println("转账成功!");
    }

二、基于注解

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: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/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 注册bean -->
    <bean name="userDao" class="com.xiaobiti.dao.impl.UserDaoImpl"/>
    <bean name="xmlAdvice" class="com.xiaobiti.demo.xmlAdvice"/>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!-- 数据库驱动 -->
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <!-- 连接数据库url -->
        <property name="url" value="jdbc:mysql://localhost/spring?useUnicode=true&amp;characterEncoding=utf-8&amp;serverTimezone=Asia/Shanghai" />
        <property name="username" value="root"/><!-- 连接数据库用户名 -->
        <property name="password" value="1234"/><!-- 连接数据库密码 -->
    </bean>
    <!-- 配置jdbc模板 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 默认必须使用数据源 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 注册bean -->
    <bean id="accountDao" class="com.xiaobiti.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <!--开启自动代理支持-->
    <aop:aspectj-autoproxy/>

    <!-- 4.事务管理器,依赖于数据源 -->
    <bean id="transactionManager" class= "org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" /></bean>

    <!-- 5.编写通知,需要编写对切入点和具体执行事务细节-->
    <!-- 基于注解方式 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- 6.编写aop,使用AspectJ的表达式,让spring自动对目标生成代理-->
    <aop:config>
        <aop:pointcut expression="execution(* com.itheima.*.*(..))"
                      id="txPointCut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

AccountDao.java

package com.xiaobiti.dao;

public interface AccountDao {
    public void transfer(String outUser,String inUser,Double money);
}

AccountDaoImpl.java

package com.xiaobiti.dao.impl;

import com.xiaobiti.dao.AccountDao;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class AccountDaoImpl implements AccountDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    // 转账 inUser:收款人; outUser:汇款人; money:收款金额
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,readOnly = false)
    public void transfer(String outUser, String inUser, Double money) {
        // 收款时,收款用户的余额=现有余额+所汇金额
        this.jdbcTemplate.update("update account set balance = balance + ? "
                + "where name = ?",money, inUser);
        // 模拟系统运行时的突发性问题
        //int i = 1/0;
        // 汇款时,汇款用户的余额=现有余额-所汇金额
        this.jdbcTemplate.update("update account set balance = balance - ?"
                + "where name = ?",money, outUser);
    }
}

测试运行代码:

public static void main(String[] args) {
        ApplicationContext applicationContext =
                new ClassPathXmlApplicationContext("applicationContext.xml");
        // 获取AccountDao实例
        AccountDao accountDao =
                (AccountDao)applicationContext.getBean("accountDao");
        // 调用实例中的转账方法
        accountDao.transfer("李四", "张三", 100.0);
        // 输出提示信息
        System.out.println("转账成功!");
    }

 

标签:事务管理,AccountDao,applicationContext,Spring,jdbcTemplate,money,public,String
From: https://www.cnblogs.com/xiaobiti/p/17301667.html

相关文章

  • MQTT(EMQX) - SpringBoot 整合MQTT 连接池 Demo - 附源代码 + 在线客服聊天架构图
    MQTT(EMQX)-LinuxCentOSDocker安装MQTT概述MQTT(MessageQueueTelemetryTransport)是一个轻量级传输协议,它被设计用于轻量级的发布/订阅式消息传输,MQTT协议针对低带宽网络,低计算能力的设备,做了特殊的优化。是一种简单、稳定、开放、轻量级易于实现的消息协议,在物联网......
  • SpringBoot整合RocketMQ,老鸟们都是这么玩的!
    今天我们来讨论如何在项目开发中优雅地使用RocketMQ。本文分为三部分,第一部分实现SpringBoot与RocketMQ的整合,第二部分解决在使用RocketMQ过程中可能遇到的一些问题并解决他们,第三部分介绍如何封装RocketMQ以便更好地使用。1.SpringBoot整合RocketMQ在SpringBoot中集成RocketMQ......
  • SpringMVC中使用引入jquery不能加载页面
    今天在学习springMVC的json数据绑定时,需要使用到jquery发送ajax请求。但是当我通过是<script>标签引入了jquery.js。但是当我访问该jsp的时候就是不显示页面的内容我一直以为时SpringMVC的servelt拦截器拦截了静态资源,但是我过滤了静态资源还是不显示。后来才发现,我把<script......
  • 优化Spring MVC消息转换器实现精度和时间转换
    重写ObjectMapper/***对象映射器:基于jackson将Java对象转为json,或者将json转为Java对象*将JSON解析为Java对象的过程称为[从JSON反序列化Java对象]*从Java对象生成JSON的过程称为[序列化Java对象到JSON]*/publicclassJacksonObjectMapperextendsObjectMapper{......
  • 【springboot中使用拦截器】
    1.拦截器原理1.定义拦截器:2.配置拦截器3.解决静态资源被拦截2.拦截器使用实例2.1判断用户有没有登录2.2取消拦截操作1.拦截器原理拦截器的原理很简单,是AOP的一种实现,专门拦截对动态资源的后台请求,即拦截对控制层的请求。使用场景比较多的是判断用户是否有权限请求后台,更拔高一层的......
  • 【spring学习笔记】(二)Spring MVC注解配置 参数转换注解@RequestMapping@RequestParam
    @TOC介绍在SpringMVC项目中,<\context:component-scan>配置标签还会开启@Request-Mapping、@GetMapping等映射注解功能(也就是会注册RequestMappingHandler-Mapping和RequestMappingHandlerAdapter等请求映射和处理等组件),但是<context:component-scan>不支持数据转换或验证等注解功......
  • Spring Framework面试题
    Spring与SpringFramework以及SpringBoot之间的是什么关系。Spring是一个广泛应用于Java开发的企业级开源框架。它的设计初衷是通过依赖注入(DependencyInjection,DI)和面向切面编程(AspectOrientedProgramming,AOP)等技术,简化Java应用程序的开发、测试和部署。Spring提......
  • SpringSecurity之WebSecurity和HttpSecurity
    SpringSecurity启动过程中有两个重要的类。分别是WebSecurity和HttpSecurity。 看看WebSecurity的定义:publicfinalclassWebSecurityextendsAbstractConfiguredSecurityBuilder<Filter,WebSecurity>implementsSecurityBuilder<Filter>,ApplicationContextAware,Servl......
  • SpringSecurity源码之WebSecurity构建FilterChainProxy
    主要参考了https://mp.weixin.qq.com/s/D0weIKPto4lcuwl9DQpmvQ。SpringSecurity版本是2.7.9。将SpringBoot和SpringSecurity结合使用,SpringSecurity自动配置类是SecurityAutoConfiguration.class。 @AutoConfiguration@ConditionalOnClass({DefaultAuthenticationEventPubli......
  • SpringBoot集成WebSocket
    SpringBoot集成WebSocket参考https://www.cnblogs.com/xuwenjin/p/12664650.html前言:WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC6455,并由RFC7936补充规范。WebSocketAPI也被W3C定为标准。WebSocket使得客户端和服务......