×

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

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Java Delete File

There are two techniques to erase a record in Java: Utilizing File.delete() technique.Utilizing File.deleteOnExit() technique. Using File.delete() technique: In Java, we can erase a document by utilizing the File.delete() technique for File class....

2 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

How to Convert int to double in Java

How to Convert int to double in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

URLConnection Class

What is the URL? URL stands for Uniform Resource Locator, is used to specify addresses on the World Wide Web. A URL relates to the identification of any resource connected to the web. URL syntax: Protocol://hostname/other_information(files...

6 minutes read.

Constructor Overloading in Java

In Java, constructors can be overloaded just like methods. The idea of having multiple constructors with various parameter sets so that each function Object()  can carry out a particular task...

3 minutes read.

Duodecimal in Java

Duodecimal is a notation style in which a number with a base of 12 is referred to be a duodecimal number. In Java, we can use to convert duodecimal integers...

2 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.

Java Tutorial

What is Java? Java is an object-oriented, robust, secured and platform-independent programming language. With the help of Java Programming, we can develop console, window, web, enterprise and mobile applications. Java language was...

22 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.