1. 程式人生 > >配置跨資料庫的事務控制

配置跨資料庫的事務控制

1 匯入包

 

2 配置XML檔案

 

<?xml version="1.0"encoding="UTF-8"?>

<web-app version="3.0"xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <display-name

></display-name>

    <!-- log4jConfigLocationlog4j配置檔案存放路徑 -->

    <context-param>

        <param-name>log4jConfigLocation</param-name>

        <param-value>/WEB-INF/classes/log4j.properties</param-value>

    </context-param>

 

內容如下:

# Configure logging for testing:optionally with log file

log4j.rootLogger=WARN, stdout

# log4j.rootLogger=WARN, stdout,logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n

log4j.appender.logfile=org.apache.log4j.FileAppender

log4j.appender.logfile.File=target/spring.log

log4j.appender.logfile.layout=org.apache.log4j.PatternLayout

log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

3寫類方法

package com.util;

import java.sql.Connection;

import java.sql.SQLException;

import javax.naming.NamingException;

import javax.sql.XAConnection;

import javax.transaction.UserTransaction;

import org.enhydra.jdbc.standard.StandardXADataSource;

import org.objectweb.jotm.Jotm;

import org.objectweb.transaction.jta.TMService;

/**

 * 分散式業務處理類

 *

 * @authorAdministrator

 *

 */

public class JotmHelper {

    public finalString YHConn = "YHConn";// 連線YH

    public finalString LocalConn = "LocalConn";// 連線本地

    private staticString url = "";

    private staticString user = "";

    private staticString pwd = "";

    privateTMService jotm;

    privateUserTransaction userTransaction;

    privateXAConnection xaconn = null;

    //InitialContext ctx = null;// new InitialContext();

    //

    publicJotmHelper() {

    }

    /**

     * @param connName資料庫名稱

     * @return

     * @throws Exception

     */

    publicConnection getConnection(String connName) throws Exception {

        StandardXADataSourcexads = new StandardXADataSource();

        // ctx = newInitialContext();

        // 本地

        if(connName.equals("LocalConn")) {

            // 獲取配置檔案類

            DBasePropertiesdProperties = new DBaseProperties();

            url =dProperties.GetPropertiesUrl().trim();// 獲取URL

            user =dProperties.GetPropertiesUser().trim();// 獲取資料庫登入名稱

            pwd =dProperties.GetPropertiesPwd().trim();// 獲取資料庫登入密碼

            // SQL2005

            xads.setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//

            // 驅動查詢

            xads.setUrl(url);

            xads.setTransactionManager(jotm.getTransactionManager());

            xaconn =xads.getXAConnection(user, pwd);

        }

        // YH物流

        else if(connName.equals("YHConn")) {

            // 獲取配置檔案類

            YHDBasePropertiesyHProperties = new YHDBaseProperties();

            url =yHProperties.GetPropertiesUrl().trim();// 獲取URL

            user =yHProperties.GetPropertiesUser().trim();// 獲取資料庫登入名稱

            pwd =yHProperties.GetPropertiesPwd().trim();// 獲取資料庫登入密碼

            // SQL2005

            xads.setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//

            // 驅動查詢

            xads.setUrl(url);

            xads.setTransactionManager(jotm.getTransactionManager());

            xaconn =xads.getXAConnection(user, pwd);

            // intlevel=0;

            // xaconn.getConnection().setTransactionIsolation(level);

        }

        returnxaconn.getConnection();

    }

    /**

     * 啟動事務管理服務

     */

    public voidstartTMService() {

        try {

            // 例項化事務管理器

            jotm =new Jotm(true, false);

            userTransaction= jotm.getUserTransaction();

        } catch(NamingException e1) {

            e1.printStackTrace();

        }

    }

    /**

     * 停止事務管理服務

     */

    public voidstopTMService() {

        jotm.stop();

        jotm = null;

    }

    /**

     * 事務開始

     */

    public voidbegin() {

        try {

            userTransaction.begin();

        } catch(Exception e) {

            e.printStackTrace();

        }

    }

    /**

     * 事務提交

     */

    public voidcommit() {

        try {

            userTransaction.commit();

        } catch(Exception e) {

            e.printStackTrace();

        }

    }

    /**

     * 事務回滾

     */

    public voidrollback() {

        try {

            userTransaction.rollback();

        } catch(Exception e) {

            e.printStackTrace();

        }

    }

    /**

     * 關閉資料庫連線

     */

    public voidcloseConn() {

        try {

            if(xaconn != null) {

                xaconn.close();

            }

        } catch(SQLException e) {

            e.printStackTrace();

        }

    }

}

呼叫

public boolean addPurchase(En_Purchase enPurchase) {

        //

        long start =System.currentTimeMillis();

        jotmHelper = newJotmHelper();

        enPurchaseDao= new En_PurchaseDao();

        enPurchaseDetaileDao= new En_PurchaseDetaileDao();

        boolean flag= false;

        booleanoperbool = false;

        introwsCount = 0;

        try {

            jotmHelper.startTMService();//開啟事務

            Connectionconn = jotmHelper.getConnection("LocalConn");// 本地

            //開始事務

            jotmHelper.begin();

            // 獲取是否存在相同記錄

            rowsCount= enPurchaseDao.getPurchaseCountById(enPurchase.getPur_Id().trim(), conn);

            if(rowsCount == 0) {

                // 新增Dispatch主表

                operbool= enPurchaseDao.addPurchase(enPurchase, conn);// 新增

            } elseif ((rowsCount > 0)) {

                operbool= enPurchaseDao.updateEnPurchase(enPurchase, conn);// 修改

            }

            // 如果主表插入成功

            if(operbool == true) {

                if(enPurchase.getEnPurchaseDetaileList() != null &enPurchase.getEnPurchaseDetaileList().size() > 0) {

                    //給集合連結串列賦值

                    List<En_PurchaseDetaile>tempList = enPurchase.getEnPurchaseDetaileList();

                    //新增Dispatch明細

                    flag= enPurchaseDetaileDao.addPurchaseDetaile(tempList, conn);//

                    jotmHelper.commit();//提交

                    flag= true;

                    longend = System.currentTimeMillis();

                    System.out.println("addPurchase:\t"+ "commit...");

                    System.out.println("執行時間:"+ (end - start) + "毫秒");

                }

            }

        } catch(Exception e) {

            flag =false;

            jotmHelper.rollback();

        } finally {

            jotmHelper.stopTMService();//

            jotmHelper.closeConn();

        }

        return flag;

    }