1. 程式人生 > >多語句事務操作

多語句事務操作

查詢 qpi dial SDR style location 導致 ucf 數據庫

  要求: 向數據庫中插入兩條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"
/>

[email protected]

    @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.不使用事務支持, [email protected] 事務

 執行時,拋出相同異常, 但是更新成功 .

技術分享
綜上, 使用此方法可以以事務方式同時操作兩條sql.

  方法二 : 應用場景是, 操作一條數據, 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後的列

技術分享

多語句事務操作