多语句事务操作

  要求: 向数据库中插入两条SQL, 要求一条失败, 事务回滚.
  环境: spring boot
  方法一 : 第一个想到spring的事务机制 -----  @Transactional , 使用之前需要对transactionManager进行配置, 我这边是配置在dataSource的文件, applicationContext.xml文件中 , 引入注解是事务,

①在配置文件中引入<tx:>命名空间

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

②声明使用注解式事务,注意声明事务管理

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

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

③在需要事务支持的方法上注明@Transactional

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, timeout = 3)
    public void updateBrandInfo(OuterBrandInfo OuterBrandInfo) {
        OuterBrandInfo outer = new OuterBrandInfo();
        outer.setBrandId("0001212");outer.setOuterOrderType(2);outer.setBrandName("养乐多");
        outerBrandInfoMapper.updateByPrimaryKey(outer);//更新操作 
        outerBrandInfoMapper.insert(OuterBrandInfo);//插入操作 , 设置的主键重复, 插入失败 , 更新操作会进行回滚 , 更新失败 
    }

测试结果:
1.使用事务支持,   执行过程中抛出重复主键异常org.springframework.dao.DuplicateKeyException, 跟新失败, 看出数据库未改变

2.不使用事务支持,  去掉@Transactional 事务

 执行时,抛出相同异常, 但是更新成功 .


综上, 使用此方法可以以事务方式同时操作两条sql.

注:在 private 的方法中, @Transactional 失效

spring boot 全注解使用事务: 启动类加 @EnableTransactionManagement

  方法二 :  应用场景是,  操作一条数据,  if 存在,  update ;  else insert

  第一个想法是,使用事务操作呀, 先进行查询,有就更新,没有添加. 然而貌似不能解决,两条线程操作 ----  第二条用户添加的动作,发生在第一条的查询之后,添加之前; 会导致第一条直接添加失败. 此情况就是相当于多个用户同时再插入同一条数据了嘛, try catch 处理吧.

  那是不是就需要进行两步操作了, 查询 --- 判断 --- 添加/update.   使用的mysql数据库, insert into ... ON DUPLICATE KEY 可以来帮忙 ,

eg.  

insert into t_duplicate values (1,3,4),(2,2,2),(3,3,2) on DUPLICATE key update b =values(b),c=values(c);

插入多条数据 , if主键重复, update  b = xxxx,  c=xxxxx,  只会更新配置在update后的列

     

原文地址:https://www.cnblogs.com/wangshuyu/p/6884035.html