• 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 ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

Transaction management

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.
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:

sql1 = "UPDATE" + tablename +
" SETBALANCE = "+ balance +
" WHEREACCTNUM = "+ accountnum;
tablename=tableNames [totype];
sql2 = "UPDATE " + tablename+
amount + "WHEREACCTNUM = " +

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:

execute (sql1);
execute (sql2)

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
    Bookmark Topic Watch Topic
  • New Topic