非託管環境下用Tyrex整合Hibernate和jdbc實現JTA事務

來源:互聯網
上載者:User

非託管環境下用Tyrex整合Hibernate和jdbc實現JTA事務

最近在把Hibernate整合進公司產品中,公司產品使用tyrex提供JTA事務支援,自己基於JDBC實現了一套O/R Mapping,並且嵌入了tomcat,所以事務這部分是自己實現的,與tomcat的環境無關,為非託管環境下的jta,和spring對jotm的整合類似。正常的用jdbc寫法如下:

boolean transaction = false;
Connection = connection = null;
try {
    transaction = TransactionUtil.begin();
    connection = ConnectionFactory.getConnection("localoracle");
    //此處執行jdbc操作
} catch (Exception e) {
    TransactionUtil.rollback();
} finally {
    if (connection != null) {
        connection.close();
    }
    TransactionUtil.commit(transaction);
}

為了整合hibernate自己實現了一個ConnectionProvider:

package com.company.bpms.client.hibernate;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.connection.ConnectionProvider;
import com.company.entity.ConnectionFactory;
import com.company.entity.GenericEntityException;
import com.company.util.Debug;

public class BPConnectionProvider implements ConnectionProvider {
    private String helperName = null;
    private static final String module = BPConnectionProvider.class.getName();

    public String getHelperName() {
        return helperName;
    }

    public void setHelperName(String helperName) {
        this.helperName = helperName;
    }

    public void configure(Properties properties) throws HibernateException {
        if (helperName == null) {
            helperName = (String)properties.get("bpms.helperName");
        }
        if (helperName == null) {
            throw new HibernateException("helperName not configured.");
        }
        Debug.logInfo("bpms.helperName: " + helperName, module);
    }

    public Connection getConnection() throws SQLException {
        try {
            return ConnectionFactory.getConnection(helperName);
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
            throw new SQLException(e.getMessage());
        }
    }

    public void closeConnection(Connection connection) throws SQLException {
        connection.close();
    }

    public boolean supportsAggressiveRelease() {
        return false;
    }

    public void close() throws HibernateException {
    }
}

還有一個hibernate.transaction.manager_lookup_class類:

package com.company.bpms.client.hibernate;

import java.util.Properties;
import javax.transaction.TransactionManager;
import org.hibernate.HibernateException;
import org.hibernate.transaction.TransactionManagerLookup;
import com.company.entity.TransactionFactory;

public class TyrexTransactionManagerLookup implements TransactionManagerLookup {
    public TransactionManager getTransactionManager(Properties arg0) throws HibernateException {
        TransactionManager manager = TransactionFactory.getTransactionManager();
        if (manager == null) {
            throw new HibernateException("Could not obtain Tyrex transaction manager instance");
        }
        return manager;
    }

    public String getUserTransactionName() {
        return null;
    }
}

一個Hibernate協助類:

package com.company.bpms.client.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.company.util.Debug;

public class HibernateUtil {
    private static SessionFactory sessionFactory;
    private static final String module = HibernateUtil.class.getName();

    public static SessionFactory getSessionFactory() throws Exception {
        if (sessionFactory == null) {
            synchronized (HibernateUtil.class) {
                if (sessionFactory == null) {
                    try {
                        sessionFactory = new Configuration().configure().buildSessionFactory();
                    } catch (Exception e) {
                        Debug.logError(e, module);
                        throw e;
                    }
                }
            }
        }
        return sessionFactory;
    }
}

設定檔:

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

<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.provider_class"> com.company.bpms.client.hibernate.BPConnectionProvider </property>
        <property name="bpms.helperName">localoracle</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</property>
        <property name="hibernate.transaction.manager_lookup_class"> com.company.bpms.client.hibernate.TyrexTransactionManagerLookup </property>

        <!--
            <property name="hibernate.hbm2ddl.auto">create</property>
        -->
        <mapping resource="test/entity/User.hbm.xml" />
        <mapping resource="test/entity/UserProfile.hbm.xml" />
    </session-factory>
</hibernate-configuration>

範例程式碼:

boolean transaction = false;
org.hibernate.Session session1 = null;
org.hibernate.Session session2 = null;
try {
    transaction = TransactionUtil.begin();
    session1 = HibernateUtil.getSessionFactory().getCurrentSession();
    //session1 = HibernateUtil.getSessionFactory().openSession();
    User user = new User();
    user.setUsername("aaa");
    session1.save(user);
    session1.flush();
    //session1.close();
    BugTypeOperate.createBugType(UtilMisc.toMap("bugtypeId", user.getUserId(), "bugtypeName", "bbb"));
    session2 = HibernateUtil.getSessionFactory().getCurrentSession();
    //session2 = HibernateUtil.getSessionFactory().openSession();
    UserProfile profile = new UserProfile();
    profile.setUserId(user.getUserId());
    profile.setCompanyAddress("aaaaaaa");
    session2.save(profile);
    session2.flush();
    //session2.close();
    out.print("OK");
} catch (Exception e) {
    Debug.logError(e);
    out.print("Error");
    TransactionUtil.rollback();
} finally {
    /*    
    if (session1 != null && session1.isOpen()) {
        Debug.logInfo("-------->colse session1");    
        session1.close();
        Debug.logInfo("--------> finish close session1");    
    }
 
    if (session2 != null && session2.isOpen()) {    
        Debug.logInfo("-------->colse session2");    
        session2.close();    
        Debug.logInfo("--------> finish close session2");    
    */
    TransactionUtil.commit(transaction);
}

其中使用getCurrentSession()方法,在最後提交事務時候此session會自動關閉,不需手動關閉session。如果使用 openSession()方法則需要手動關閉開啟的session。BugTypeOperate.createBugType()方法是我們自己的 JDBC實現,現在可以和Hibernate放到一個事務裡面了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.