A database transaction in any relational database management system (RDBMS) is a sequence of one or more SQL operations that are executed as a single unit of work. The primary characteristics and properties of transactions are encapsulated in the ACID principles:
- Atomicity: Ensures that all operations within the transaction are completed successfully. If any operation fails, the entire transaction is rolled back, and the database state is left unchanged.
- Consistency: Guarantees that a transaction will bring the database from one valid state to another. The database must be consistent before and after the transaction.
- Isolation: Ensures that concurrently executed transactions do not affect each other. The intermediate state of a transaction is invisible to other transactions.
- Durability: Once a transaction is committed, it will remain so, even in the event of a system failure.
Using JDBC API in the code snippet below we can check whether a database support transaction or not:
package org.kodejava.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
public class TransactionSupportChecker {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "kodejava";
private static final String PASSWORD = "s3cr*t";
public static void main(String[] args) {
try (Connection connection =
DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
DatabaseMetaData metadata = connection.getMetaData();
boolean supported = metadata.supportsTransactions();
System.out.println("Product Name : " + metadata.getDatabaseProductName());
System.out.println("Supports Transaction: " + supported);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Output of the code snippet:
Product Name : MySQL
Supports Transaction: true
Maven Dependencies
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.4.0</version>
</dependency>
