java--spring6基于注解的声明式事务

一、配置xml的数据库配置和基本配置

jdbc.url=jdbc:mysql://10.0.2.4:63306/test1111111?useUnicode=true&characterEncoding=utf-8&useSSL=false
jdbc.username=gac_trav
jdbc.password=gac@6666
jdbc.driverClassName=com.mysql.cj.jdbc.Driver

<?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
       http://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.ruqi.tx"></context:component-scan>
    <!--引入外部属性文件,创建数据源对象-->
    <context:property-placeholder location="classpath:jdbc.propries"></context:property-placeholder>
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
    </bean>
    <!--创建jdbcTemplate对象,注入数据源-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="druidDataSource"></property>
    </bean>

    <!--创建事务管理器,注入数据源-->
    <bean id = "transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"></property>
    </bean>
    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

二、模拟业务场景,建立相关的类

1、contrller层

package com.ruqi.tx.controller;

import com.ruqi.tx.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class BookController {

    @Autowired
    private BookService bookService;

    public void buyBook(Integer userId, Integer bookId){

        bookService.buyBooks(userId,bookId);
    }
}

2、service层

package com.ruqi.tx.service;
import com.ruqi.tx.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BookServiceImpl implements BookService{

    @Autowired
    private BookDao bookDao;

    @Transactional //添加在方法上,只对方法生效,放在类上则对整个类的方法生效,当方法出现异常时,进行数据回滚
    @Override
    public void buyBooks(Integer userId, Integer bookId) {
        //查询书本价格
        Integer price = bookDao.querqyPrice(bookId);
        // 更新书本库存
        bookDao.updateBookStock(bookId);
        //更新用户余额
        bookDao.updateUserBalace(userId,price);
    }
}

3、dao层

package com.ruqi.tx.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class BookDaoImpl implements BookDao{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Integer querqyPrice(Integer bookId) {
        String sql = "select price from t_book where book_id = ?";
        Integer price = jdbcTemplate.queryForObject(sql, Integer.class,bookId);
        return price;
    }

    @Override
    public void updateBookStock(Integer bookId) {
        String sql = "update t_book set stock = stock - 1 where book_id = ?";
        jdbcTemplate.update(sql, bookId);
    }

    @Override
    public void updateUserBalace(Integer userId, Integer price) {
        String sql = "update t_user set balance = balance - ? where user_id = ?";
        jdbcTemplate.update(sql, price, userId);
    }
}

4、测试类

package com.ruqi.tx;
import com.ruqi.tx.controller.BookController;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

@SpringJUnitConfig(locations = "classpath:beans.xml")
public class Testcase {

    @Autowired
    private BookController bookController;

    @Test
    public void testBuyBook(){
        bookController.buyBook(1,1);
    }
}

二、事务属性

@Transactional(readOnly = true) :表示该事务只能使用查询操作
@Transactional(timeout = 3):表示该事务超过3s没完成,则会超时进行回滚
@Transactional(noRollbackFor = ArithmeticException.class):指出现某种异常,将该异常的类加上去时,此时不回滚
@Transactional(noRollbackForClassName = "java.lang.ArithmeticException"):同上,指定类的全路径
//@Transactional(noRollbackForClassName = "java.lang.ArithmeticException")
@Transactional(noRollbackFor = ArithmeticException.class)
@Override
public void buyBooks(Integer userId, Integer bookId) {

    //查询书本价格
    Integer price = bookDao.querqyPrice(bookId);
    // 更新书本库存
    bookDao.updateBookStock(bookId);
    System.out.println(1/0);
    //更新用户余额
    bookDao.updateUserBalace(userId, price);
}

@Transactional(propagation = Propagation.REQUIRED):传播行为,表示有两个方法A(),B(),A循环调用B,两个方法都有事务注解,其中B加了传播行为,则表示,当调用A时,把A和B当做一个整体作为事务处理,只要出现异常,则全部回滚
@Transactional(propagation = Propagation.REQUIRES_NEW):传播行为,表示有两个方法A(),B(),A循环调用B,两个方法都有事务注解,其中B加了传播行为,则表示,当调用A时,B每次开了一个独立的事务,相互不影响,该通过通过,该回滚回滚

三、全注解注入事务注解

1、将xml文件的内容注释,使用以下配置类,其他一致

package com.ruqi.tx;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;

@Configuration
@ComponentScan("com.ruqi.tx")
@EnableTransactionManagement //开启事务管理
public class SpringConfig {

    @Bean
    public DataSource getDataSource(){
        DruidDataSource dataSource1 = new DruidDataSource();
        dataSource1.setUrl("jdbc:mysql://10.0.2.4:63306/test1111111?useUnicode=true&characterEncoding=utf-8&useSSL=false");
        dataSource1.setUsername("gac_trave");
        dataSource1.setPassword("gac@6666");
        dataSource1.setDriverClassName("com.mysql.cj.jdbc.Driver");
        return dataSource1;
    }

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

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

2、测试类 

package com.ruqi.tx;
import com.ruqi.tx.controller.BookController;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class testcase {

    @Test
    public void testBuyBook1(){
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        BookController bookController1 = context.getBean("bookController",BookController.class);
        Integer[] bookids = {1,2};
        bookController1.buytwoBooks(1,bookids);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

郑*杰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值