• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

Transaction management

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How to manage transactions without EJBs in a plain java class?

Thanks You.
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Note to self: don't get into a fist fight with a cactus. Command this tiny ad to do it:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic