Local database reading edition

How to use UserTransaction in Servlet?

Reconstructed from database records, not a captured original forum layout. Dates and display names are retained as recorded; timezone and real-world identity are not inferred. Historical advice, contact details and offers are not current. Original markup is shown as inert text.

Forum index · Java - GUI/JSP/Servlet

Opening post

Suresh · 2001-02-15 14:29:02

I have a servlet with two methods which updates the database. I want to put these two methods in one transaction using javax.transaction.UserTransaction. Any sample code is highly appreciated. Thanks in advance. Suresh Sharma

Reply 3

Asha · 2001-02-15 15:43:47

There are 5 steps to consider when you do transaction using UserTransaction. <ul> <li>Importing Packages </li> <li>Initializing the UserTransaction Object </li> <li>Using JNDI to Return an Object Reference to the UserTransaction Object </li> <li>Starting a Transaction </li> <li>Completing a Transaction </li> </ul> I want to make sure certain points before i discuss this in detail. <font color=blue> Ofcourse for a servlet to obtain a UserTransaction object, there must be a JTS-capable server to deliver the object. A servlet Can not maintain a JTA UserTransaction object across multiple servlet invocations.(i thing you got my point, multiple s=thread excuting the service method). A JTA transaction must start and finish within a single invocation (service() method). </font id=blue> Here is the sample code <pre id=code><font face=courier size=2 id=code> import javax.naming.*; import javax.transaction.*; public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ Context ctx = new InitialContext(); UserTransaction utx = (UserTransaction)ctx.lookup(&quot;javax.jts.UserTransaction&quot;); try{ utx.begin(); // perform multiple operations... // call the two methods which updates the DB utx.commit(); }catch(Exception exe){ if(utx!=null) try{ utx.rollback(); }catch(Exception e){} } } </font id=code></pre id=code> Hope this helps Asha Balasubramanyan http://www.ammu.org

Source notes

MyCommunity/nandighosha.org.zip!/forum/tools/snitz_forums_2000.mdb
Table: FORUM_TOPICS + FORUM_REPLY · record IDs: 38, 3