首页 > 解决方案 > 如何在 Rx-java2 jdbc 中提交多个 sql 查询的事务?

问题描述

我正在尝试使用 rxjava2-jdbc 将 sql 记录插入到多个记录中。请让我知道如何实现这一目标。我尝试了以下步骤,但没有成功。

情况1)

public class DatabaseRepository {

    private Database db;

    public DatabaseRepository() throws Exception{

        NonBlockingConnectionPool pool =
                Pools.nonBlocking()
                        .maxPoolSize(Runtime.getRuntime().availableProcessors() * 5)
                        .connectionProvider(ConnectionProvider.from("jdbc:oracle:thin:@//rcld19-scan.test.com:1522/TGCD01", "test", "testPassword"))
                        .build();

        this.db = Database.from(pool);

    }

        public Flowable<Integer> insertIntoMultipleTables() {

               Flowable<Integer> insertIntoEmployee=db.update(insert into employee(name, designation) values ("Employee_1","Manager"))
                    .counts()
                    .doOnError(e -> {
                        log.error("Exception while inserting record to employee table: {}", e.getMessage());
                    });

               return db.update(insert into department(name, no_of_employees) values("Management",1))
                    .dependsOn(insertIntoEmployee)
                    .counts()
                    .doOnError(e -> {
                        log.error("Exception while inserting record to department table: {}", e.getMessage());
                    });
        }
}

我正在尝试作为单个事务的一部分插入多个表。在这种情况下,将记录插入部门表失败不会从第一个表回滚数据

案例2)

public class DatabaseRepository {

    private Database db;

    public DatabaseRepository() throws Exception{

        NonBlockingConnectionPool pool =
                Pools.nonBlocking()
                        .maxPoolSize(Runtime.getRuntime().availableProcessors() * 5)
                        .connectionProvider(ConnectionProvider.from("jdbc:oracle:thin:@//rcld19-scan.test.com:1522/TGCD01", "test", "testPassword"))
                        .build();

        this.db = Database.from(pool);

    }
    public Flowable<Tx<Integer>> insertIntoMultipleTables(){

            Flowable<Tx<Integer>>  insertIntoEmployee= db.update(insert into employee(name, designation) values ("Employee_1","Manager"))             
                    .transacted()
                    .counts()
                    .flatMap(tx ->{
                        return tx.update(insert into department(name, no_of_employees) values("Management",1))
                                .counts()
                                .doOnError(e -> log.error("Exception while inserting record to department table: {}",
                                        e.getMessage()));

                    })
                    .doOnError(e -> {
                        log.error("Exception while inserting record to employee table: {}", e.getMessage());
                    });

        }
}

此代码不能用作事务。插入中的任何 SQL 错误,都不会回滚插入到其他表中的记录

我的要求是使用反应式 java2-jdbc 我需要将记录插入到多个数据库表中,我无法在 Git 中找到任何有效的示例。如果我需要做任何不同的事情,请告诉我。

标签: reactive-programmingrx-java2

解决方案


推荐阅读