import java.io.*; import java.util.*; import java.sql.*; import javax.sql.*; import oracle.jdbc.xa.OracleXid; import oracle.jdbc.xa.client.*; import javax.transaction.xa.*; public class DistributedTransaction { public static Xid createXid (int p_bID) throws XAException { byte[] l_gID = new byte[1]; // Global ID l_gID[0] = (byte) 9; // Set Global Id to 9 byte[] l_bID = new byte[1]; // Branch ID l_bID[0] = (byte) p_bID; // Set branch ID to the parameter passed byte[] l_globalID = new byte[64]; byte[] l_branchID = new byte[64]; // Copy the Global ID and branch ID to a 64 bit string System.arraycopy (l_gID, 0, l_globalID, 0, 1); System.arraycopy (l_bID, 0, l_branchID, 0, 1); // Call OracleXid() to generate the Xid Xid l_xid = new OracleXid(0x1234, l_globalID, l_branchID); // Return the Transaction ID return l_xid; } public static void main (String args[]) throws SQLException { OracleXADataSource ds1 = new OracleXADataSource (); OracleXADataSource ds2 = new OracleXADataSource (); ds1.setURL ("jdbc:oracle:thin:@antarctica:1521:mydb"); ds2.setURL ("jdbc:oracle:thin:@arctic:1521:yourdb"); // Verbindung mit Hilfe des Connection-Pools aufbauen XAConnection xacon1 = ds1.getXAConnection ("tux", "pingus"); XAConnection xacon2 = ds2.getXAConnection ("tux", "pingus"); Connection c1 = xacon1.getConnection (); Connection c2 = xacon2.getConnection (); // Transaktionsressourcen ermittlen XAResource xares1 = xacon1.getXAResource (); XAResource xares2 = xacon2.getXAResource (); // globale Transaktions-ID erzeugen Xid xid1 = createXid (1); Xid xid2 = createXid (2); // ... und starten xares1.start (xid1, XAResource.TMNOFLAGS); xares2.start (xid2, XAResource.TMNOFLAGS); // Statement erzeugen String updStmt = "UPDATE book SET price = price * 0.9"; Statement stmt1 = c1.createStatement (); Statement stmt2 = c2.createStatement (); // ... und ausführen stmt1.executeUpdate (updStmt); stmt2.executeUpdate (updStmt); // Suspend xares1.end (xid1, XAResource.TMSUCCESS); xares2.end (xid2, XAResource.TMSUCCESS); // Transaktionen auf Commit vorbereiten int prep1 = xares1.prepare (xid1); int prep2 = xares2.prepare (xid2); if (prep1 == XAResource.XA_OK && prep2 == XAResource.XA_OK) { // Commit durchführen xares1.commit (xid1, false); xares2.commit (xid2, false); } else { // Transaktionen zurücksetzen xares1.rollback (xid1); xares2.rollback (xid2); } } }