This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes EJB and other Java EE Technologies and the fly likes Transaction management Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "Transaction management" Watch "Transaction management" New topic
Author

Transaction management

lakshmi pokala
Greenhorn

Joined: Mar 04, 2006
Posts: 3
How to manage transactions without EJBs in a plain java class?

Thanks You.
Pratheep Nair
Greenhorn

Joined: Sep 20, 2005
Posts: 14
Every time you execute a SQL statement in JDBC, by default JDBC provides a transaction. However most of the time this default behavior is not sufficient and it is your responsibility to define the transactional boundaries.

The default behavior, where each statement is contained within its own transaction, is controlled by the connection's autocommit mode. When autocommit is enabled, each change is committed to the database automatically. When you disable autocommit, you become responsible for defining the start and end of a transaction which lets you determine whether to commit or rollback the entire transaction. To disable a connection's auto-commit mode, call the setAutoCommit() method, which accepts a single Boolean parameter.

For e.g:

conn.setAutoCommit(false);
sql1 = "UPDATE" + tablename +
" SETBALANCE = "+ balance +
" WHEREACCTNUM = "+ accountnum;
stmt.executeUpdate(sql1);
tablename=tableNames [totype];
sql2 = "UPDATE " + tablename+
" SETBALANCE = BALANCE + " +
amount + "WHEREACCTNUM = " +
accountnum;
stmt.executeUpdate(sql2);
conn.commit();

When you call commit(), the current transaction ends and, if possible, all changes made prior to the call are saved. However, if the database is unable to save any one of the changes, then none of them are saved.

You can wrap the execution inside a try-catch block and call rollback on the connection whenever an exception happens:

try
{
.............
execute (sql1);
.............
execute (sql2)
conn.commit();
}
catch
{
conn.rollback()
}

These are just simple cases. When you are dealing with mutiple users trying to access the database at the same time (most real world scenarios) you have to consider lot of other transaction isolation levels.

EJBs is not the only way to implement transactions. Even Spring framework supports transactions.
 
GeeCON Prague 2014
 
subject: Transaction management