1. 程式人生 > >hibernate與ssm多數據源配置

hibernate與ssm多數據源配置

eterm rac t_sql 1.0 事務 res 調度 dia oca

hibernate:

1.配置多個數據源,比如2個:hibernate.cfg1.xml~hibernate.cfg8.xml

技術分享圖片
<?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">

<!--
Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect">com.standsoft.dialect.DialectForInkfish</property> <property name="connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=zhangyanandb</
property> <property name="connection.username">sa</property> <property name="connection.password">111111</property> <property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property> <property name
="myeclipse.connection.profile">sql2008-4</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <mapping resource="com/standsoft/DictArea.hbm.xml" /> </session-factory> </hibernate-configuration>
View Code

2.配置兩個sessionfactory

技術分享圖片
package com.orm;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the current
 * thread of execution. Follows the Thread Local Session pattern, see
 * {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory1{

    /**
     * Location of hibernate.cfg.xml file. Location should be on the classpath
     * as Hibernate uses #resourceAsStream style lookup for its configuration
     * file. The default classpath location of the hibernate config file is in
     * the default package. Use #setConfigFile() to update the location of the
     * configuration file for the current session.
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg1.xml";
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static Configuration configuration = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;
    static {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }

    private HibernateSessionFactory1() {
    }

    /**
     * Returns the ThreadLocal Session instance. Lazy initialize the
     * <code>SessionFactory</code> if needed.
     *
     * @return Session
     * @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = threadLocal.get();

        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession() : null;
            threadLocal.set(session);
        }

        return session;
    }

    /**
     * Rebuild hibernate session factory
     *
     */
    public static void rebuildSessionFactory() {
        try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory();
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }

    /**
     * Close the single hibernate session instance.
     *
     * @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

    /**
     * return session factory
     *
     */
    public static org.hibernate.SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * return session factory
     *
     * session factory will be rebuilded in the next call
     */
    public static void setConfigFile(String configFile) {
        HibernateSessionFactory1.configFile = configFile;
        sessionFactory = null;
    }

    /**
     * return hibernate configuration
     *
     */
    public static Configuration getConfiguration() {
        return configuration;
    }

}
View Code

3.配置調度類sessionfactory

技術分享圖片
package com.orm;

import org.hibernate.HibernateException;
import org.hibernate.Session;

/**
 * Configures and provides access to Hibernate sessions, tied to the current
 * thread of execution. Follows the Thread Local Session pattern, see
 * {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {
    public static Session currentSession;
    

    public static Session getCurrentSession() {
        return currentSession;
    }


    public static void setCurrentSession(Session currentSession) {
        HibernateSessionFactory.currentSession = currentSession;
    }


    public static Session getSession() throws HibernateException {
        return currentSession;
    }
}
View Code

4.切換數據源

HibernateSessionFactory.setCurrentSession(HibernateSessionFactory1.getSession());

HibernateSessionFactory.setCurrentSession(HibernateSessionFactory2.getSession());

以上就是純hibernate的多數據源配置操作,已驗證可以使用。但覺得哪兒有問題,也沒測出來,希望大佬指正

ssm:

1.配置多個數據源,比如2個:resource/db.properties

技術分享圖片
jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:sqlserver://localhost:1433; DatabaseName=zhangyanandb
jdbc.username=sa
jdbc.password=11111

jdbc2.url=jdbc:sqlserver://localhost:1433; DatabaseName=zhangyanandb2
jdbc2.username=sa
jdbc2.password=11111
View Code

2.交給spring管理兩個數據庫連接

技術分享圖片
    <!-- 數據庫連接池 -->
    <!-- 加載配置文件 -->
    <context:property-placeholder location="classpath:resource/db.properties" />
    <!-- 數據庫連接池 -->
    <bean id="dataSource1" class="com.alibaba.druid.pool.DruidDataSource"
        destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="maxActive" value="10" />
        <property name="minIdle" value="5" />
    </bean>

        <!-- 數據庫連接池 -->
    <bean id="dataSource2" class="com.alibaba.druid.pool.DruidDataSource"
        destroy-method="close">
        <property name="url" value="${jdbc2.url}" />
        <property name="username" value="${jdbc2.username}" />
        <property name="password" value="${jdbc2.password}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="maxActive" value="10" />
        <property name="minIdle" value="5" />
    </bean>
    
     <!-- 動態數據源 -->
<bean id="dynamicDataSource" class="util.DynamicDataSource">
    <property name="targetDataSources">  
        <map key-type="java.lang.String">
            <!-- 指定lookupKey和與之對應的數據源 -->
            <entry key="dataSource1" value-ref="dataSource1"></entry>  
            <entry key="dataSource2" value-ref="dataSource2"></entry>
        </map>  
    </property>  
    <!-- 這裏可以指定默認的數據源 -->
    <property name="defaultTargetDataSource" ref="dataSource1" />  
</bean>
View Code

3.spring配置sessionfactory

技術分享圖片
    <!-- 配置sqlsessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
        <property name="configLocation" value="classpath:resource/SqlMapConfig.xml"></property>
        <property name="dataSource" ref="dynamicDataSource"></property>
    </bean>
    
View Code

4.配置事物

技術分享圖片
<!-- 事務管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 數據源 -->
        <property name="dataSource" ref="dynamicDataSource" />
    </bean>
    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 傳播行為 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="create*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>
View Code

5.配置DynamicDataSource類及DynamicDataSourceHolder類供選擇調用

技術分享圖片
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {

    /**
     *  該方法返回需要使用的DataSource的key值,
     *  然後根據這個key從resolvedDataSources這個map裏取出對應的DataSource,
     *  如果找不到,則用默認的resolvedDefaultDataSource。
     */
    @Override
    protected Object determineCurrentLookupKey() {
        // 從自定義的位置獲取數據源標識
        return DynamicDataSourceHolder.getDataSource();
    }

}
View Code 技術分享圖片
public class DynamicDataSourceHolder {
    /**
     * 註意:數據源標識保存在線程變量中,避免多線程操作數據源時互相幹擾
     */
    private static final ThreadLocal<String> THREAD_DATA_SOURCE = new ThreadLocal<String>();

    public static String getDataSource() {
        return THREAD_DATA_SOURCE.get();
    }

    public static void setDataSource(String dataSource) {
        THREAD_DATA_SOURCE.set(dataSource);
    }

    public static void clearDataSource() {
        THREAD_DATA_SOURCE.remove();
    }

}
View Code

6切換數據源

DynamicDataSourceHolder.setDataSource("dataSource1");

DynamicDataSourceHolder.setDataSource("dataSource2");

hibernate與ssm多數據源配置