spring事务操作--基础知识

事务概念
1.什么是事务
(1)事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败
(2)例如微信转账:我转账100给你,我少100,你多100
2.事务的四个特性(ACID)
(1)原子性
(2)一致性
(3)隔离性
(4)持久性

搭建事务操作环境
1.在Service(业务操作):创建转账的方法(1)调用dao两个方法
2.在Dao(数据库操作):创建两个方法(1)少钱的方法(2)多钱的方法

Service注入dao,在dao注入JdbcTemplate,在JdbcTemplate 注入 DataSource

事务操作(spring事务管理介绍)
1.事务添加到JavaEE三层结构里面的Service层(业务逻辑层)
2.在Spring进行事务管理操作
(1)有两种方式:编程式事务管理和声明式事务管理(主用)
3.声明式事务管理
(1)基于注解方式(主用)
(2)基于xml 配置文件方式
4.在Spring进行声明式事务管理,底层使用AOP
5.Spring 事务管理 API
(1)提供一个接口(PlatformTransactionManager),代表事务管理器,这个接口针对不同的框架提供不同的实现类

注解声明式事务管理
1.在spring 配置文件配置事务管理器
2.在spring配置文件,开启事务注解
(1)在spring 配置文件引入名称空间 tx
3.在service 类上面(获取service类里面方法上面)添加事务注解
(1)@Transactional,这个注解添加到类上面,也可以添加到方法上面
(2)填加在类上面,这个类里面所有的方法都添加了事务

@Transactional配置事务的相关参数
1.propagation:事务传播行为
(1)多事务方法直接进行调用,这个过程中事务是如何进行管理的
(2)事务方法:对数据库表数据进行变化的操作(增删改查)
(3)Spring框架事务传播行为有7种
①REQUIRED (默认)
如果add方法本身有事务,调用update方法之后,update使用当前add方法里面事务
如果add方法本身没有事务,调用update方法之后,创建新事务
②REQUIRED_NEW
使用add方法调用update方法,无论add方法本身有没有事务,都会创建新事务

2.ioslation:事务隔离级别
(1)事务具有隔离性,多事务操作之间不会产生影响。不考虑隔离性产生很多问题
(2)有三个读问题:脏读,不可重复读,虚(幻)读
①脏读:一个未提交事务读取到了另一个未提交事务的数据
②不可重复读:一个未提交事务读取到了另一个提交事务修改数据
③虚读:一个未提交事务读取到另一个提交事务添加的数据
(3)设置隔离级别解决读的问题
①(读未提交)READ UNCOMMITTED(脏读,不可重复读,虚读)
②(读已提交)READ COMMITTED(不可重复读,虚读)
③(可重复读)REPEATABLE_READ(虚读)(默认)
④(串行化)SERIALIZABLE(无)

3.timeout:超时时间
(1)事务需要在一定时间内进行提交,如果不提交进行回滚
(2)默认值是-1,设置时间以秒为单位进行计算

4.readOnly:是否只读
(1)读:查询操作,写:添加删除修改操作
(2)默认值false

5.rollbackFor:回滚
(1)设置出现哪些异常进行事务回滚

6.noRollbackFor:不回滚
(1)设置出现哪些异常进行事务回滚

<?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 http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://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"></context:component-scan>

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<!--        <property name="url" value="jdbc:mysql:///user_db"></property>-->
        <property name="url" value="jdbc:mysql://localhost:3306/user_db?serverTimezone=UTC"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    </bean>
    <!-- JdbcTemplate对象 -->
    <bean id="jabcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 注入dataSource -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 创建事务管理器 -->
    <bean id = "transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
package com.service;

import com.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserService {
    //注入Dao
    @Autowired
    private UserDao userDao;
    //转账方法
    public void accountMoney(){
//        try{
            //第一步开启事务

            //第二步,进行业务操作
            //han少一百
            userDao.reduceMoney();
            //模拟异常
            int i = 10/0;
            //xixi多一百
            userDao.addMoney();

            //第三步,没有发生异常,提交事务

//        }catch (Exception e){
            //第四步,出现异常,事务回滚

//        }
        
    }
}
package com.dao;

public interface UserDao {
    //多钱
    public void addMoney();
    //少钱
    public void reduceMoney();
}
package com.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    //注入JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;
    //多钱
    @Override
    public void addMoney() {
        String sql = "update t_account set money=money+? where username=?";
        jdbcTemplate.update(sql, 100, "xixi");
    }
    //少钱(转账)
    @Override
    public void reduceMoney() {
        String sql = "update t_account set money=money-? where username=?";
        jdbcTemplate.update(sql, 100, "han");
    }
}
package com.test;

import com.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestMoney {
    @Test
    public void testAccount(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = applicationContext.getBean("userService", UserService.class);
        userService.accountMoney();
    }
}

事务操作(XML声明式事务管理)
1.在spring配置文件中配置
(1)配置事务管理器
(2)配置通知
(3)配置切入点和切面

<?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 http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://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"></context:component-scan>


    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<!--        <property name="url" value="jdbc:mysql:///user_db"></property>-->
        <property name="url" value="jdbc:mysql://localhost:3306/user_db?serverTimezone=UTC"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    </bean>
    <!-- JdbcTemplate对象 -->
    <bean id="jabcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!-- 注入dataSource -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 创建事务管理器 -->
    <bean id = "transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 开启通知 -->
    <tx:advice id="txadvice">
        <!-- 配置事务参数 -->
        <tx:attributes>
            <!-- 指定哪种规则的方法上面添加事务 -->
<!--name指定方法名        <tx:method name="account*"/>-->
            <tx:method name="accountMoney" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置切入点和切面 -->
    <aop:config>
        <!-- 配置切入点 -->
        <aop:pointcut id="pt" expression="execution(* com.service.UserService.*(..))"/>
        <!-- 配置切面 -->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt"></aop:advisor>
    </aop:config>

</beans>

事务操作(完全注解声明式事务管理)
1.创建配置类,使用配置类替换xml配置文件。有配置类就不要配置文件,配置文件中也有事务管理器,会产生异常。

package com.config;

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;

@Configuration  //配置类
@ComponentScan(basePackages = "com")    //开启注解扫描
@EnableTransactionManagement    //开启事务
public class TxConfig {
    //创建数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/user_db?serverTimezone=UTC");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }
    //创建JdbcTemplate对象
    @Bean
    public JdbcTemplate getJdbcTemplate(DruidDataSource dataSource){
        //到IOC容器中根据类型找到dataSource
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //注入dataSource
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }
    //创建事务管理器
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DruidDataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值