1. 程式人生 > >XA和程式設計式的事務程式碼解決!

XA和程式設計式的事務程式碼解決!

 Connection has already been created in this tx context for pool named jnboracle.
 Illegal attempt to create connection from another pool: testpool
 怎麼辦?database is oracle !


1。connection pool必須是擴充套件了tx的DriveClass,如:drive classname:oracle.jdbc.xa.client.OracleXADataSource;
2。DataSource 必須是TxDataSource。
3。程式碼中從jndi中取得相應的DataSource,進行操作便OK

至於具體console操作你該知道咯!

以下是我的Transaction測試程式碼
---------------------------------
public class JDBCTransaction{
    public final String UT_JNDI_Name = "javax.transaction.UserTransaction";
    public final String DS_JNDI_Name1 = "AndyDS1";
    public final String DS_JNDI_Name2 = "AndyDS2";
   
    private Hashtable ht = null;
    private Context ctx = null;
    private UserTransaction ut = null;
   
    private Connection conn1 = null;
    private Connection conn2 = null;
    private Statement stmt1 = null;
    private Statement stmt2 = null;
   
    private Context getInitialContext()throws NamingException{
        ht = new Hashtable();
        ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        ht.put(Context.PROVIDER_URL, "t3://andy:7001");
        return new InitialContext(ht);
    }
   
    public void CreateNewRecord(int id, String name, int age, String status) {
        String SQL = "";
        try{
            ctx = getInitialContext();
            ut = (UserTransaction)ctx.lookup(UT_JNDI_Name);
            ut.begin();
            DataSource ds1 = (DataSource)ctx.lookup(DS_JNDI_Name1);
            conn1 = ds1.getConnection();
            DataSource ds2 = (DataSource)ctx.lookup(DS_JNDI_Name2);
            conn2 = ds2.getConnection();
            conn1.setAutoCommit(false);
            conn2.setAutoCommit(false);
            stmt1 = conn1.createStatement();
            stmt2 = conn2.createStatement();
            SQL = "insert into t1 values(" + id + ", '" + name + "', '" + status + "')";
            stmt1.executeQuery(SQL);
            System.out.println("SQL: " + SQL);
            SQL = "insert into t2 values(" + id + " ," + age + ")";
            stmt2.executeQuery(SQL);
            System.out.println("SQL: " + SQL);
            ut.commit();
            System.out.println("Transaction commit !");
        }
        catch(Exception e){
         e.printStackTrace();
         try{
           ut.rollback();
          System.out.println("Transaction rollback !");
         }
         catch(Exception e1){
           e1.printStackTrace();
         }
        }
    }
}
你可以用我的程式碼試一試,我沒遇到問題。