125_Java_Spring5_JdbcTemplate__transaction

举报
alexsully 发表于 2021/08/12 19:23:57 2021/08/12
【摘要】 jdbctemplate_事物操作

1 事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败
2 事务四个特性(ACID)原子性, 一致性, 隔离性, 持久性


Spring事务管理操作

1 事务添加到 JavaEE 三层结构里面 Service 层(业务逻辑层)
2 在 Spring 进行事务管理操作 两种方式:编程式事务管理和声明式事务管理(使用)
3 声明式事务管理
 (1)基于注解方式
 (2)基于xml配置文件方式

4 在Spring进行声明式事务管理,底层使用 AOP 原理
 Spring 事务管理 API 提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类

 1 在spring配置文件配置事务管理器
 2 在spring配置文件开启事务注解
 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.alex"></context:component-scan>
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

<!--    数据库连接池-->
    <bean id="datasource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${prop.driverClass}"></property>
        <property name="url" value="${prop.url}"></property>
        <property name="username" value="${prop.userName}"></property>
        <property name="password" value="${prop.password}"></property>
    </bean>

    <!-- JdbcTemplate 对象 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <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>

 在 service 类上面(或者 service 类里面方法上面)添加事务注解
 (1)@Transactional,这个注解添加到类上面,也可以添加方法上面
 (2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务
 (3)如果把这个注解添加方法上面,为这个方法添加事务 (仅限 public 方法)

事务操作(注解)
在 service 类上面添加注解@Transactional,在这个注解里面可以配置事务相关参数

 propagation 事务传播行为 多事务方法直接进行调用

@Transactional(propagation=Propagation.REQUIRED):如果有事务,那么加入事务,没有的话新建一个(默认情况下)
@Transactional(propagation=Propagation.REQUIRES_NEW):不管是否存在事务,都创建一个新的事务,原来的挂起,新的执行完毕,继续执行老的事务

@Transactional(propagation=Propagation.NOT_SUPPORTED):容器不为这个方法开启事务
@Transactional(propagation=Propagation.MANDATORY):必须在一个已有的事务中执行,否则抛出异常 
@Transactional(propagation=Propagation.NEVER):必须在一个没有的事务中执行,否则抛出异常(与Propagation.MANDATORY相反)
@Transactional(propagation=Propagation.SUPPORTS):如果其他bean调用这个方法,在其他bean中声明事务,那就用事务,如果其他bean没有声明事务,那就不用事务

2 ioslation:事务隔离级别
  (1)事务有特性成为隔离性,多事务操作之间不会产生影响。不考虑隔离性产生很多“读”问题:脏读/不可重复读/幻读
     脏读: 一个未提交事务读取到另一个未提交事务的数据
     不可重复读: 一个未提交事务读取到另一提交事务修改数据
     虚读: 一个未提交事务读取到另一提交事务添加数据
  解决:通过设置事务隔离级别,解决读问题

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

4 readOnly:是否只读, 默认值false,表可读/写操作 ,设置readOnly值是true,代表只能查询(读操作)
5 rollbackFor:回滚 设置出现哪些异常进行事务回滚
6 noRollbackFor:不回滚 ;设置出现哪些异常不进行事务回滚


config

@Configuration //配置类
@ComponentScan(basePackages = "com.alex") //组件扫描
@EnableTransactionManagement //开启事务
public class TxConfig {
    
    //创建数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///t_spring?useSSL=false&characterEncoding=utf8");
        dataSource.setUsername("root");
        dataSource.setPassword("szc.2020");
        return dataSource;
    }
    

    //创建JdbcTemplate对象
    // 在 IOC 容器中已经存在 datasource对象, 类似 @Autowired,在容器中找到 datasource 进行注入
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        //到ioc容器中根据类型找到dataSource
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //注入dataSource
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //创建事务管理器
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}


DAO

public interface UserDao {
    //多钱
    public void addMoney();
    //少钱
    public void reduceMoney();
}


@Repository
public class UserDaoImpl implements UserDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void addMoney() {
        String sql = "update t_account set money=money-? where username=?";
        jdbcTemplate.update(sql,100,"alex");

    }

    @Override
    public void reduceMoney() {
        String sql = "update t_account set money=money+? where username=?";
        jdbcTemplate.update(sql,100,"sully");
    }
}

service

@Service
@Transactional (readOnly = false,timeout = -1,propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class UserService {
    @Autowired
    private UserDao userDao;
    public void accountMoney() {
        userDao.reduceMoney();
        //模拟异常
        int i = 10/0;
        userDao.addMoney();
    }
}


   @Test
    public void test1(){

        AnnotationConfigApplicationContext context1 = new AnnotationConfigApplicationContext(TxConfig.class);
        UserService userService = context1.getBean("userService", UserService.class);
        userService.accountMoney();
    }


事务操作(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 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.alex"></context:component-scan>

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql:///user_db" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </bean>

    <!-- JdbcTemplate对象 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

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

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

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

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。