Set Transaction Isolation in Java Connection with Example



In a database system, where more than one transaction is being executed simultaneously and in parallel, the property of isolation states that all the transactions will be carried out and executed as if it is the only transaction in the system. No transaction will affect the existence of any other transaction.

Transaction Isolation Levels in Java Connection

JDBC (Java Database Connectivity) provides support 5 transaction isolation levels through Connection interface.

  • TRANSACTION_NONE: It is represented by integer value 0 does not support transactions.
  • TRANSACTION_READ_COMMITTED: It is represented by integer value 2 supports transactions allowing Non-Repeatable Reads and, Phantom Reads.
  • TRANSACTION_READ_UNCOMMITTED: It is represented by integer value 1 supports transactions allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads.
  • TRANSACTION_REPEATABLE_READ: It is represented by integer value 4 supports transactions allowing only Phantom Reads.
  • TRANSACTION_SERIALIZABLE: It is represented by integer value 8 supports transactions without allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads.

setTransactionIsolation() Method

The setTransactionIsolation() method of the Connection interface is used to change the transaction isolation level for the current connection.

Parameters

This method accepts an integer value representing one of the 5 transaction isolation levels.

Example

Given below is an example of the setTransactionIsolation() method -

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connection_setTransactionIsolation {
    public static void main(String args[]) throws SQLException {
        //Registering the Driver
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        //Getting the connection
        String url = "jdbc:mysql://localhost/mydatabase";
        Connection con = DriverManager.getConnection(url, "root", "password");
        System.out.println("Connection established......");
        //Retrieving the transaction isolation level
        con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        int transactionIsoltionLevel = con.getTransactionIsolation();
        System.out.println("Transaction isolation level of the underlying
        database is: "+transactionIsoltionLevel);
    }
}

Output

Connection established......
Transaction isolation level of the underlying database is: 1
Updated on: 2024-07-05T17:40:49+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements