×

Transaction Management in java

Definition: A database application is an application that is running against a relational database and executes one or more transactions.

A transaction is an executing program that contains some database operations, like reading or applying insertions, deletions, or updates to the database.

Transaction example:

package com.STH.JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
public class Transaction_Management {
public static void main(String[] args) throws ClassNotFoundException {
//Select the Query to get the Data from employee table
String QUERY = "select * from employee where empNum = 1";
String QUERY1 = "select * from employee where empNum = 2";
Boolean autoCommit;
String update_query = "update employee set salary = 40000 where empNum = 1"; 
String update_query1 = "update employee set salary = 50000 where empNum = 2"; 
//Update the query to set the dept id for the employee whose empNUM is 3
Class.forName("oracle.jdbc.driver.OracleDriver"); 
try(Connection conn = DriverManager.getConnection("jdbc:oracle:thin:system/pass123@localhost:1521:XE"))
{
Statement statemnt1 = conn.createStatement();
ResultSet rs1 =null;
rs1 = statemnt1.executeQuery(QUERY); 
//Executed the SELECT Query
System.out.println("Getting the data from employee_details table");
displayData(rs1);
System.out.println("Setting the AutoCommit value as FALSE");
conn.setAutoCommit(false);
autoCommit = conn.getAutoCommit();
System.out.println("AutoCommit value of the Connection = "+ autoCommit);
statemnt1 = conn.createStatement();
System.out.println("Executing Update query to update salary of EMPNUM = 1");
System.out.println("Update Query is " + update_query);
int return_rows = statemnt1.executeUpdate(update_query);
System.out.println("Update the data but didn't commit");
Connection conn1 = DriverManager.getConnection("jdbc:oracle:thin:system/pass123@localhost:1521:XE");
System.out.println("Opening new connection");
System.out.println("EMPNUM = 1 data");
Statement statement2 = conn1.createStatement();
ResultSet rs;
rs = statement2.executeQuery(QUERY); 
displayData(rs);
System.out.println("Commit has been done");
conn.commit();
Savepoint s1 = conn.setSavepoint();
System.out.println("SavePoint has been created");
System.out.println("Displaying data of EMPNUM = 1");
System.out.println("Using the Second Connection");
rs = statement2.executeQuery(QUERY); 
displayData(rs);
rs = statemnt1.executeQuery(QUERY); 
//Rollback the transaction
System.out.println("Data of EMPNUM = 2");
rs1 = statemnt1.executeQuery(QUERY1); 
displayData(rs1); 
System.out.println("Updating the salary of EMPNUM = 2");
System.out.println("Update Query is " + update_query1);
statemnt1.executeUpdate(update_query1);
System.out.println("Data of EMPNUM = 2 but didn't commit");
rs1 = statemnt1.executeQuery(QUERY1); 
displayData(rs1);
System.out.println("Rollback is done... so updated data won't be reflected");
conn.rollback(s1);
System.out.println("Data of EMPNUM = 2 after Rollback till the last savepoint");
rs1 = statemnt1.executeQuery(QUERY1); 
displayData(rs1);
}
catch (SQLException e) {
e.printStackTrace();
}
}
public static void displayData(ResultSet rs1) throws SQLException
{
while(rs1.next())
{
int empNum = rs1.getInt("empNum");
String lastName = rs1.getString("lastName");
String firstName = rs1.getString("firstName");
String email = rs1.getString("dept");
String deptNum = rs1.getString("deptNum");
String salary = rs1.getString("salary");
System.out.println(empNum + "," +lastName+ "," +firstName+ "," +dept +","+deptNum +"," +salary);
}
}
}

Acid Properties of Transactions:

  1. Atomicity: If every program works correctly without any errors, then everything gets committed to the database. If any of the parts of the execution of the transaction gets rolled back, then it will not commit.
  2. Consistency: The consistency property is a property that if any database was in a consistent state before and after the execution of a transaction, the database will also be in a consistent state.
  3. Isolation: In this property, multiple transactions will execute concurrently, the system says that for every pair of transactions. It will execute one after the other pair.
  4. Durability: Durability ensures that, once a transaction has been committed even if there is a system failure or crash, the transaction’s update does not lose.

Transaction methods:

MethodDescription
void setAutoCommit(boolean status)In this method, It is true by default means each transaction is committed by default.
void commit()It is used to commit the transaction.
void rollback()It is used to cancel the transaction.

Transaction management in JDBC using statement:

import java.sql.*; 
class Records{ 
public static void main(String args[])throws Exception{ 
Class.forName("oracle.jdbc.driver.OracleDriver"); 
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); 
con.setAutoCommit(false); 
Statement stmt=con.createStatement(); 
stmt.executeUpdate("insert into user420 values(1,'hari',40000)"); 
stmt.executeUpdate("insert into user420 values(2,'Raju',50000)"); 
con.commit(); 
con.close(); 
}} 

Transaction management in JDBC using preparedStatement:

import java.sql.*; 
import java.io.*; 
class TM{ 
public static void main(String args[]){ 
try{ 
Class.forName("oracle.jdbc.driver.OracleDriver"); 
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); 
con.setAutoCommit(false); 
PreparedStatement ps=con.prepareStatement("insert into user 420 values(?,?,?)"); 
BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
while(true){ 
System.out.println("enter id"); 
String s1=br.readLine(); 
int id=Integer.parseInt(s1); 
System.out.println("enter name"); 
String name=br.readLine(); 
System.out.println("enter salary"); 
String s3=br.readLine(); 
int salary=Integer.parseInt(s3); 
ps.setInt(1,id); 
ps.setString(2,name); 
ps.setInt(3,salary); 
ps.executeUpdate(); 
System.out.println("commit/rollback"); 
String answer=br.readLine(); 
if(answer.equals("commit")){ 
con.commit(); 
} 
if(answer.equals("rollback")){ 
con.rollback(); 
} 
System.out.println("Want to add more records y/n"); 
String ans=br.readLine(); 
if(ans.equals("n")){ 
break; 
} 
} 
con.commit(); 
System.out.println("record successfully saved"); 
con.close();//before closing connection commit() is called 
}catch(Exception e){System.out.println(e);} 
}
} 

Related Topics

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.

Annotations in Java

Annotations in Java Java Annotations are metadata about the source code. They do not have any direct effect on the execution of the java program. Annotations in Java were introduced in...

4 minutes read.

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Class definition in Java

The class definition in Java Java is an object-oriented programming language. We essentially know that programming languages based on object-oriented paradigms have classes and objects in their concepts as main, which...

6 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

2 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution...

1 minute read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

ArrayList vs Vector in Java

ArrayList Vs. Vector in Java In Java, the two classes ArrayList and Vector both are associated with Java Collections Framework. Both classes implement java.util.List interface. Even so, these classes have noticeable...

4 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.