Very basic question for a newbie in JTA
Hello,
I would like to implement DB transaction using JTA implementation of my app server (Weblogic 6.1). If there are n statements, I want them all to be executed and succeed. If one fails, all the changes made to the DB need to be rolled back. Very simple. The most basic transaction you can think of.
My code which you can see below, gets a context from the app server, create a UserTransaction object, gets a connection and a statement and finally executes the statements.
- Autocommit has to be set to false for the connection (since we want all or none of the statements to succeed).
The problem
I get a return code from the executeUpdate method that 1 row was inserted. But, when I check the DB, nothing is inserted in it. Can someone please tell me why? Thanks.
Code
--
import javax.transaction.UserTransaction;
import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import java.util.*;
import weblogic.jndi.*;
public class JTATest {
public static void main(String args[]){
Context ctx = null;
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, "t3://localhost:7001");
env.put(Context.SECURITY_PRINCIPAL, "system");
env.put(Context.SECURITY_CREDENTIALS, "");
try {System.out.println("Loading Initial Context...");
ctx = new InitialContext(env);
System.out.println("Done loading Initial Context");
UserTransaction txn = (UserTransaction) ctx.lookup("javax.transaction.UserTransaction");
try {
txn.begin();
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("DCMDataSource");
Connection con = ds.getConnection();
con.setAutoCommit(false);
Statement stmt = con.createStatement();
System.out.println("Got connection and statement");
int i = stmt.executeUpdate("insert into yahoo values(1,'foo')");
stmt.close();
txn.commit();
System.out.println("Committed Transaction");
}
catch(SQLException se){
se.printStackTrace(System.err);
try {
txn.rollback();
} catch (javax.transaction.SystemException se){
se.printStackTrace(System.err); }
}
catch(javax.transaction.NotSupportedException txnNotSupported){
txnNotSupported.printStackTrace(System.err);
}
catch(javax.transaction.RollbackException re){
re.printStackTrace(System.err);
}
catch(javax.transaction.SystemException sysExcep){
sysExcep.printStackTrace(System.err);
}
catch(javax.transaction.HeuristicMixedException he){
he.printStackTrace(System.err);
}
catch(javax.transaction.HeuristicRollbackException her){
her.printStackTrace(System.err);
}
}
catch(NamingException ne){
ne.printStackTrace(System.err);
}
}
}

