rspec/rules/S6912/java/rule.adoc
2024-02-23 09:32:59 +01:00

69 lines
2.2 KiB
Plaintext

== Why is this an issue?
Executing a batch of SQL queries instead of individual queries improves performance by reducing communication overhead with the database.
Batching SQL statements is beneficial in common situations where a SQL statement is executed within a loop.
In such cases, adding the statement to a batch and subsequently executing it reduces the number of interactions with the database.
This results in improved efficiency and faster execution times.
The rule raises an issue when it detects a `java.sql.Statement` being executed within a loop instruction, such as `for`, `while` or the `forEach` method of `java.lang.Iterable`, `java.util.Map` and `java.util.stream.Stream`.
== How to fix it
Group SQL statements by using the method `addBatch` to add them to a batch and then execute them using `executeBatch` to send them to the database in a single call.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
public void execute(Connection connection) {
try {
Statement statement = connection.createStatement();
for (int i = 0; i < 10; i++) {
statement.execute("INSERT INTO myTable (column1, column2) VALUES (" + i + ", 'value" + i + "')"); // Noncompliant
}
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
public void execute(Connection connection) {
try {
Statement statement = connection.createStatement();
for (int i = 0; i < 10; i++) {
statement.addBatch("INSERT INTO myTable (column1, column2) VALUES (" + i + ", 'value" + i + "')"); // Compliant
}
statement.executeBatch();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
----
== Resources
=== Documentation
* https://docs.oracle.com/en/java/javase/21/docs/api/java.sql/java/sql/Statement.html[Oracle Java SE 21 API - java.sql.Statement]
* https://docs.oracle.com/en/java/javase/21/docs/api/java.sql/java/sql/PreparedStatement.html[Oracle Java SE 21 API - java.sql.PreparedStatement]
=== Articles & blog posts
* https://www.baeldung.com/jdbc-batch-processing[Baeldung - JDBC Batch Processing]