Transaction Management
Transaction
Transaction is the process of performing multiple database operations as one Atomic
unit with all or Nothing Criteria i.e.
o When all the database operations in the unit are successful then Transaction
is successful and should be commited.
o When any one database operation in the unit is failed then Transaction is
failed and should be rolled back.
When you implement transactions properly in your application, It gaurantees ACID
Properties.
A - Atomacity
C - Consistency
I - Isolation
D – Durability
1) Atomacity
Atomacity = Definition of Transaction
Consider the salary transfer
1000 deposits + 1 withdraw => Totally Salary transfer contains 1001 DB Operations.
When all these 1001 database operations are successful then Transaction is
successful and all 1001 DB Operations have to be commited.
When any one DB operation is failed then Transaction is failed and all DB Operations
have to be rolled back.
2) Consistency
When you are running the transaction, you may enforce many business rules as per
the application requirement.
Your application should be consistent when any business rule is failed otherwise you
may get some inconsistent results.
Consider the withdraw operation:
Some business rules are
1) Minimum balance is 5K.
2) if (ATM){
a) Only 5 withdrawals per day.
b) Limit: 50K per day.
}
3) if (Branch){
a) Only 10 withdrawals per day.
b) Limit: 5L per day.
}
When you are implementing the Transaction, You can implement code for Business
rules inside transaction. When any Business rule is failed, then Transaction will be
forced to rollback.
Java Learning Center 150 Hibernate5 Study Guide
3) Isolation
You can run multiple transactions concurrently.These concurrently running
multiple txs should not distrub other transactions i.e. multiple transactions should
run isolately or independently without affecting each other.
Case A:
Multiple transactions running concurrently are using multiple Account rows of
accounts table.
Customer 1 having Account Number 99.
Customer 2 having Account Number 88
Customer 3 having Account Number 77
At a time, following operations are happening.
1) Transaction 1- trsnafer (withdrawal). - Uses 99
2) Transaction 2- bank teller (withdrawal or deposit). - Uses 88
3) Transaction 3- loan EMI (withdrawal). - Uses 77
No Problems in the case.
Case B:
Multiple transactions running concurrently are using single Account row of accounts
table.
Customer 1 having Account Number 99 and Balance 15K
At a time, following operations are happening.
1) Transaction 1-trsnafer (withdrawal). - Uses 99
2) Transaction 2-bank teller (withdrawal or deposit). - Uses 99
3) Transaction 3-loan EMI (withdrawal). - Uses 99
In this case,
o 3 Transactions are running concurrently and using single column or row or
table which may cause problems.
The problems coming when multiple transactions running concurrently are called as
Transactional Concurrency Problems.
There are three Transactional Concurrency Problems
1) Dirty Read Problem
2) Repeatable Read Problem
3) Phantom Read Problem
To avoid these Transactional Concurrency Problems, You have to apply one of the
following required Transactional Isolation Levels.
1) READ_UNCOMMITTED 1
2) READ_COMMITTED 2
3) REPEATABLE_READ 4
4) SERIALIZABLE 8
Java Learning Center 151 Hibernate5 Study Guide
4) Durability
Your enterprise data should be available for long time i.e. as long as your enterprise
application is running.
You have to protect your enterprise data from crashes, failures etc.
You have to implement proper backup and you can make your enterprise data
durable with recovery mechanisam and proper logging mechanisam.
Consider the following scenario
Every one Minute the enterprise data backup is scheduled.
o 10.31A.M first backup
o Some 1000 DB operations happened
You have deposited 10L at 10.31.57
Update accounts set balance = 10L where accno=99;
o 10.31.59 but crashed at this point.
o 10.32A.M next backup
Transactional Concurrency Problems
1) Dirty Read Problem
When TRANSACTION reads the Dirty Values (i.e. modified but not commited) then
you may get some inconsistent results.
To avoid Dirty Reads, you have to lock the Column (Cell).
To Lock the Column, you have to apply Isolation Level called READ_COMMITTED.
2) Repeatable Read Problem
When a TRANSACTION is reading the same row repeatedly, you may get differenet
set of values in different reads.This kind of problem is called Repeatable Read
Problem.
To avoid Repeatable Read Problem, you have to lock the Row.
To Lock the Row, you have to apply Isolation Level called REPEATABLE_READ.
3) Phantom Read Problem
When a TRANSACTION is reading the set of rows repeatedly, you may get differenet
set of rows in different reads.This kind of problem is called Phantom Read Problem.
To avoid Phantom Reads, you have to lock the Entire Table.
To Lock the Table, you have to apply Isolation Level called SERIALIZABLE.
DIRTY REPEATABLE PHANTOM LOCK
READ READ READ
READ_UNCOMITTED NO NO NO NO LOCK
READ_COMMITTED YES NO NO COLUMN LOCK
REPEATABLE_READ YES YES NO ROW LOCK
SERIALIZABLE YES YES YES TABLE LOCK
YES -> Problem Solved NO -> Problem Not Solved
Java Learning Center 152 Hibernate5 Study Guide
Types of Transactions
1) Local Transactions
2) Distributed Transactions
1) Local Transactions
When a Single Database is participating in the transactional operations (i.e. DB
operations) then it is called as Local Transactions.
Ex:
Transfer the funds from one account to another account where two accounts are in
same bank or same database.
2) Distributed Transactions
When a two or more databases are participating in the transactional operations then
it is called as Distributed Transactions.
Ex:
Transfer the funds from one account to another account where two accounts are in
different banks or different databases.
Types of Transactions
1) Flat Transactions
2) Nested Transactions
1) Flat Transactions
Ex:
Begin Tx1
OP1
OP2
OP3
End Tx1
Note: Multiple Flat transactions running will not disturb other concurrently running
transactions.
2) Nested Transactions
Ex:
Begin Tx1
1) OP1
2) OP2
3) Begin Tx2
OP3
OP4
End Tx2
4) OP5
5) Begin Tx3
OP6
OP7
End Tx3
6) OP8
End Tx1.
Java Learning Center 153 Hibernate5 Study Guide
Note:
When Inner transaction (Tx2, Tx3) is failed then outer Transaction (Tx1) also
will be failed.
Ex: Make a Trip.
Mon - Fri
(Bangalore -> Pune -> Delhi -> Mumbai -> Bangalore)
Book the fligts
Tx begin
1) Book the flight tickets from Bangalore -> Pune (Tx1) - AI
2) Book the flight tickets from Pune -> Delhi (Tx2) - KF
3) Book the flight tickets from Delhi -> Mumbai (Tx3) - JET
4) Book the flight tickets from Mumbai ->Bangalore (Tx4) - AI
Tx end.
JDBC Hibernate JPA EJB Spring
Local Transaction YES YES (JDBC) YES (JDBC) YES (JDBC) YES (JDBC)
Distributed Transaction NO YES (CME) YES (CME) YES (CME) YES (CME)
YES
Flat Transaction YES YES YES YES
YES
Nested Transaction NO NO NO NO
CME -> Container Managed Environment
Java Learning Center 154 Hibernate5 Study Guide
When you are implementing transactions with any persistence implementations
like JDBC, Hibernate, JPA, EJB, spring then you need to learn two things.
1) How to demarcate the Transactional Boundaries.
2) How to Specify the Isolation Levels.
Managing Transaction with JDBC
1) Specifying the Transactional Boundaries
Connection con=null;
Try {
con =DriverManager.getConnstion(“..”,”..”,”..”);
OP1; (at this point, autocommit is true.)
con.setAutoCommit (false); // TX begin
OP2;
OP3;
OP4;
con.commit (); // TX end
OP5;
} catch (Exception e){
if (con!=null){
con.rollback (); // TX end
OP6;
}
} finally {
if (con!=null){
con.close ();
}
}
2) Specifying the Isolation Levels.
con.setTransactionIsolation (1/2/4/8);
con.setTransactionIsolation (Connection.REPEATABLE_READ);
Java Learning Center 155 Hibernate5 Study Guide
Managing Transaction with Hibernate
1) Specifying the Transactional Boundaries
Transaction tx =null;
try {
…
tx =session.beginTrasnaction(); //TX begin
OP1;
OP2;
OP3;
tx.commit (); // TX end
} catch (Exception e) {
if (tx!=null){
tx.rollback (); // TX end
}
} }
2) Specifying the Isolation Levels
Write the following property in hibernate.cfg.xml
<property name="hibernate.connection.isolation">1/2/4/8</property>
Hibernate Transaction Management
Transaction is an interface available in org.hibernate package and has the following
concrete implementations.
1) JDBCTransaction
2) JTATransaction
3) CMTTransaction
TransactionFactory is an interface available in org.hibernate.transaction package
and has the following concrete implementations.
1) JDBCTransactionFactory
2) JTATransactionFactory
3) CMTTransactionFactory
These TransactionFactory implementation classes are responsible for providing the
corresponding Transaction depending on the properties written by you in
hibernate.cfg.xml. i.e
1) JDBCTransactionFactory provides the JDBCTransaction
2) JTATransactionFactory provides the JTATransaction
3) CMTTransactionFactory provides the CMTTransaction
1) JDBC Transactions
By default, Hibernate uses JDBCTransactionFactory which provides
JDBCTransaction.
i.e. Default Transaction management used by hibernate system is JDBCTransactions.
To use JDBCTransactions , Connection Pooing must be
DriverManagerConnectionProvider or C3P0ConnectionProvider
Java Learning Center 156 Hibernate5 Study Guide
2) JTA Transactions
When you want to use JTA Transactions, You must check the following.
o Your Hibernate Application must run in CME (Container Managed
Environment).
o Connections must be Datasource Connections
To Use JTA Transactions, You must specify the following props in hibernate.cfg.xml.
For Weblogic Application Server:
<property name="transaction.factory_class">
org.hibernate.transaction.JTATransactionFactory
</property>
<property name="transaction.manager_lookup_class">
org.hibernate.transaction.WeblogicTransactionManagerLookup
</property>
<property name="jta.UserTransaction">java:comp/UserTransaction</property>
<property name="hibernate.current_session_context_class">jta</property>
3) CMT Transactions:
To Use CMT Transactions, you must check the following.
o Your Hibernate Application must run in CME (Container Managed
Environment).
o Connections must be Datasource Connections
To Use CMT Transactions, You must specify the following props in hibernate.cfg.xml.
For JBoss Application Server:
<property name="transaction.factory_class">
org.hibernate.transaction.CMTTransactionFactory
</property>
<property name="transaction.manager_lookup_class">
org.hibernate.transaction.JBossTransactionManagerLookup
</property>
<property name="jta.UserTransaction">java:comp/UserTransaction</property>
<property name="hibernate.current_session_context_class">jta</property>
Java Learning Center 157 Hibernate5 Study Guide