首页 > 其他分享 >spring的注解开发-事务@transactional的使用

spring的注解开发-事务@transactional的使用

时间:2024-12-01 10:32:42浏览次数:12  
标签:money spring transactional springframework context import org com 注解

新建maven项目

pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.shrimpking</groupId>
    <artifactId>demo7</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.14</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.13.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.23</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>
    </dependencies>
</project>

数据库

drop table if exists ay_account;
create table ay_account(
	id int not null auto_increment primary key comment '',
	account_name varchar(100) not null comment '',
	money int default null comment ''
) comment '账户表';
insert into ay_account values (null,'tom',5000);
insert into ay_account values (null,'jerry',5000);

accountMapper

package com.shrimpking.mapper;

import org.apache.ibatis.annotations.Param;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/2/2 20:46
 */
public interface AccountMapper
{
    public void incrMoney(@Param("accountName") String accountName,@Param("money") Integer moeny);

    public void decrMoney(@Param("accountName") String accountName,@Param("money") Integer money);
}

accountMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.shrimpking.mapper.AccountMapper">

    <update id="incrMoney">
        update ay_account set money=money+#{money}
        where account_name = #{accountName}
    </update>

    <update id="decrMoney">
        update ay_account set money=money-#{money}
        where account_name = #{accountName}
    </update>

</mapper>

accountService

package com.shrimpking.service;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/2/2 21:00
 */
public interface AccountService
{
    void transferMoney(String outAccount,String inAccount,Integer money);

    void registerAccount(String accountName);
}

accountServiceImpl

package com.shrimpking.service;

import com.shrimpking.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/2/2 21:01
 */
@Service(value = "accountService")
public class AccountServiceImpl implements AccountService
{
    @Autowired
    private AccountMapper accountMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ,timeout = -1)
    public void transferMoney(String outAccount, String inAccount, Integer money)
    {
        this.accountMapper.decrMoney(outAccount,money);
        //int i = 1/0;
        this.accountMapper.incrMoney(inAccount,money);
    }

    @Override
    public void registerAccount(String accountName)
    {

    }
}

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
       https://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.shrimpking"/>

    <!-- 加载资源文件   -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

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

    <!--    将sqlSessionFactory注入spring容器-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.shrimpking.mapper"/>
    </bean>

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

    <!--  增强通知  -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*"/>
            <!--
                     isolation隔离级别
                     propagation事务
                     timeout超时
                     read-only只读
                     -->
            <tx:method name="registerAccount" isolation="REPEATABLE_READ" propagation="REQUIRED" timeout="5" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!--  切面  -->
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.shrimpking.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>

</beans>

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

    <!-- 组件扫描   -->
    <context:component-scan base-package="com.shrimpking"/>

    <!-- 加载资源文件   -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

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

    <!--    将sqlSessionFactory注入spring容器-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.shrimpking.mapper"/>
    </bean>

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

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

</beans>

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimeZone=UTC
jdbc.username=root
jdbc.password=mysql123

txconfig

package com.shrimpking.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/2/3 10:39
 */
@Configuration
@ComponentScan({"com.shrimpking"})
@PropertySource(value = "classpath:jdbc.properties")
@MapperScan({"com.shrimpking.mapper"})
//<tx:annotation-driven transaction-manager="transactionManager"/>
@EnableTransactionManagement
public class TxConfig
{
    @Bean
    public DataSource dataSource(
            @Value("${jdbc.driver}") String driver,
            @Value("${jdbc.url}") String url,
            @Value("${jdbc.username}") String username,
            @Value("${jdbc.password}") String password
    ){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean(name = "transactionManager")
    public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }

}

apptest

package com.shrimpking;

import com.shrimpking.config.TxConfig;
import com.shrimpking.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.CollectionUtils;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Shrimpking
 * @create 2024/2/2 21:10
 */
public class AppTest
{
    public static void main(String[] args)
    {
//        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//        AccountService accountService = context.getBean(AccountService.class);
//        accountService.transferMoney("tom","jerry",500);

//        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext2.xml");
//        AccountService accountService = context.getBean(AccountService.class);
//        accountService.transferMoney("tom","jerry",500);

        ApplicationContext context = new AnnotationConfigApplicationContext(TxConfig.class);
        AccountService accountService = context.getBean(AccountService.class);
        accountService.transferMoney("tom","jerry",500);

    }

}

标签:money,spring,transactional,springframework,context,import,org,com,注解
From: https://blog.csdn.net/modern358/article/details/136005860

相关文章

  • SpringBoot集成Swagger框架
    SpringBoot集成Swagger框架引言无论是前端还是后端开发,都或多或少地被接口文档折磨过。前端经常抱怨后端给的接口文档与实际情况不一致。后端又觉得编写及维护接口文档会耗费不少精力,经常来不及更新。其实无论是前端调用后端,还是后端调用后端,都期望有一个好的接口文档。......
  • 【Spring框架 二】
    Spring框架二Spring数据访问框架Spring数据访问的核心组件使用Spring进行数据访问的方式SpringDataJPA事务SpringDataREST总结SpringSpring框架是一个开源的Java应用程序框架,它提供了一种轻量级的解决方案,用于开发企业级Java应用程序。Spring框架的核心原......
  • springboot毕设毕节教育扶贫网站程序+论文
    系统程序文件列表开题报告内容研究背景在当今社会,教育扶贫已成为国家扶贫战略的重要组成部分,旨在通过提升贫困地区的教育水平,从根本上打破贫困的代际传递。毕节地区,作为中国西南部的贫困地区之一,教育资源的匮乏一直是制约其经济社会发展的关键因素。近年来,随着信息技术的飞......
  • 从 @Import 注解到自动配置
    推荐阅读:Spring@Import注解用法、SpringBootStarter是什么@Import注解用于把实例加入SpringIOC容器中。打开@SpringBootApplication注解(SpringBoot2.6.13为例),会发现其被@EnableAutoConfiguration标注:@Target(ElementType.TYPE)@Retention(RetentionPolicy.R......
  • 【附源码】springboot租车管理系统设计与实现
    博主介绍:✌CSDN新星计划导师、Java领域优质创作者、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和学生毕业项目实战,高校老师/讲师/同行前辈交流✌技术范围:SpringBoot、Vue、SSM、HTML、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、小程序、安卓app、大数......
  • 【附源码】springboot 案件管理系统设计与实现
    博主介绍:✌CSDN新星计划导师、Java领域优质创作者、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和学生毕业项目实战,高校老师/讲师/同行前辈交流✌技术范围:SpringBoot、Vue、SSM、HTML、Jsp、PHP、Nodejs、Python、爬虫、数据可视化、小程序、安卓app、大数......
  • 基于SpringBoot动漫交流系统平台设计与实现
    收藏关注不迷路!!......
  • Java基于SpringBoot的教师教学培训管理系统的设计与实现
    收藏关注不迷路!!......
  • 基于SpringBoot流浪动物管理系统设计和实现
    收藏关注不迷路!!......
  • Java基于springboot的一个在线环保意识教育平台的设计与实现
    收藏关注不迷路!!......