public classJTA_MySQL {public static voidmain(String[] args) {
XADataSource xaDs1=JTA_MySQL.getDataSource("jdbc:mysql://172.30.60.126:3306/db_zhang", "root","root");
XAConnection xaCon1= null;
XAResource xaRes1= null;
Connection conn1= null;
Statement stmt1= null;
XADataSource xaDs2=JTA_MySQL.getDataSource("jdbc:mysql://172.30.60.124:3306/db_zhang", "root","root");
XAConnection xaCon2= null;
XAResource xaRes2= null;
Connection conn2= null;
Statement stmt2= null;int ret1 = 0;int ret2 = 0;
Xid xid1= new MyXid(100, new byte[] { 0x01 }, new byte[] { 0x02 });
Xid xid2= new MyXid(100, new byte[] { 0x01 }, new byte[] { 0x03 });try{
xaCon1=getXAConnetion(xaDs1);
conn1=getConnection(xaCon1);
stmt1=conn1.createStatement();
xaRes1=xaCon1.getXAResource();
xaCon2=getXAConnetion(xaDs2);
conn2=getConnection(xaCon2);
stmt2=conn2.createStatement();
xaRes2=xaCon2.getXAResource();
xaRes1.start(xid1, XAResource.TMNOFLAGS);
stmt1.execute("delete from person where id=1");
xaRes1.end(xid1, XAResource.TMSUCCESS);
xaRes2.start(xid2, XAResource.TMNOFLAGS);
stmt2.execute("insert into person select 1, 'zhang'");
xaRes2.end(xid2, XAResource.TMSUCCESS);
ret1=xaRes1.prepare(xid1);
ret2=xaRes2.prepare(xid2);if (XAResource.XA_OK == ret1 && XAResource.XA_OK ==ret2) {
xaRes1.commit(xid1,false);
xaRes2.commit(xid2,false);
System.out.println("提交分布式事务");
}else{
xaRes1.rollback(xid1);
xaRes2.rollback(xid2);
System.out.println("回退分布式事务");
}
}catch(SQLException e) {
e.printStackTrace();
}catch(XAException e) {
e.printStackTrace();
}
}private staticXADataSource getDataSource(String url, String user,
String password) {
MysqlXADataSource dataSource= newMysqlXADataSource();
dataSource.setUrl(url);
dataSource.setUser(user);
dataSource.setPassword(password);returndataSource;
}public staticXAConnection getXAConnetion(XADataSource dataSource) {
XAConnection XAConn= null;try{
XAConn=dataSource.getXAConnection();
}catch(SQLException e) {
e.printStackTrace();
}returnXAConn;
}public staticConnection getConnection(XAConnection XAConn) {
Connection conn= null;try{
conn=XAConn.getConnection();
}catch(SQLException e) {
e.printStackTrace();
}returnconn;
}public static voidcloseConnection(Connection conn) {try{
conn.close();
}catch(SQLException e) {
System.out.println("连接关闭失败");
}
}
}