JDBC Statement – Групповые операции (с Maven)

Групповые операции позволяют выполнять несколько запросов за одно обращение к базе данных. Минимально необходимый код:

Connection connection = getConnection();
Statement statement = connection.createStatement();

statement.addBatch(query);
statement.addBatch(query);
statement.addBatch(query);
statement.addBatch(query);

statement.executeBatch();
connection.commit();

Полный код примера со вставкой записей:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class StatementBatchInsert {
    private static final String DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
    private static final String CONNECTION_STRING = "jdbc:derby:derbyDB;create=true";

    public static void main(String[] args) throws SQLException {
        StatementBatchInsert app = new StatementBatchInsert();
        app.run();
    }

    private Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName(DRIVER_NAME);
        Connection connection = DriverManager.getConnection(CONNECTION_STRING);
        return connection;
    }

    private void run() throws SQLException {
        System.out.println("Inserting records with batch");

        Connection connection = null;
        Statement statement = null;

        try {
            connection = getConnection();
            statement = connection.createStatement();

            for (int index = 0; index < 10; index++) {
                String query = "INSERT INTO USERS_TABLE " +
                        "(USER_NAME) VALUES " +
                        "('user_" + index + "')";

                statement.addBatch(query);
            }

            statement.executeBatch();
            connection.commit();

        } catch (Exception e ){
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.close();
            }
            if (statement != null) {
                statement.close();
            }
        }

        System.out.println("Records inserted");
    }
}

В результате выполнения в консоль будет выведено сообщение:

Inserting records with batch
Records inserted

Необходимые зависимости могут быть получены с помощью Apache Maven, pom.xml приведен ниже:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>ru.mydesignstudio</groupId>
  <artifactId>statements</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <dependencies>
        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derby</artifactId>
            <version>10.12.1.1</version>
        </dependency>
    </dependencies>
</project>