简体   繁体   中英

Multi-table inserts or primary key linking in a single transaction

Using JDBC, I need to insert data into a SQL database table. However, there's a JSON payload that pretty much needs to go into a separate table so it won't weight down sorts, etc on the primary table.

For performance reasons, I want to batch insert queries - but because they're all batched I won't have the primary keys until after the batch insert has completed.

In the past I've handled them separately - storing the primary keys and then inserting data into the secondary table. However, it becomes difficult to ensure the sanity of the data. Interruptions, errors, etc can all cause a failure.

I need to include both inserts in a single transaction or find some better way to connect the records.

Currently, this is going into an H2 database, but will eventually support MySQL, and possibly postgres.

public StorageWriteResult write(List<DataContainer> containers) throws Exception {;
    PreparedStatement statement = null;

    try {
        statement = conn.prepareStatement("INSERT INTO ...");

        for (DataContainer container : containers) {
            statement.setObject(1, container.getString(DataQueries.EventName).get());
            // ...
            statement.addBatch();

            // insert data into a secondary table?
        }

        statement.executeUpdate();
    }
    finally {
        if (statement != null) {
            statement.close();
        }

        conn.close();
    }
    // ...
}

When opening the connection, make sure you don't have autocommit enabled. Then just run your two inserts and commit manually afterwards if everything went through ok, otherwise roll back. See eg https://docs.oracle.com/cd/A87860_01/doc/java.817/a83724/tips2.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM