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>

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;
} }

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;
}
}

4.参考http://www.cnblogs.com/yanan7890/p/8681566.html切换数据源

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

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>

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>

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>

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();
} }
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();
} }

6切换数据源

DynamicDataSourceHolder.setDataSource("dataSource1");

DynamicDataSourceHolder.setDataSource("dataSource2");

hibernate与ssm多数据源配置的更多相关文章

  1. mysql之整合ssm多数据源配置

    一,基于SSM框架的多数据源配置 1.创建DynamicDataSourceHolder用于持有当前线程中使用的数据源标识 public class DynamicDataSourceHolder { ...

  2. ssm多数据源配置

    1.在.properties配置文件中 添加第二个数据源信息(type2,driver2, url2,username2,pawwword2) 2.修改spring-context.xml(src/m ...

  3. JAVA spring hibernate 多数据源配置记录

    数据源配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http:// ...

  4. hibernate 在tomcat7.X 下配置mysql数据源

    先说一点题外话,LZ近期学习java web. 今天刚看到hibernate,发如今hibernate配置数据源时网上的资料都太久远了,一般以tomcat 5 版本号下的配置居多.而tomcat 7下 ...

  5. SSM框架之多数据源配置

    多数据源的应用场景:主要是数据库拆分后,怎样让多个数据库结合起来来达到业务需求. SSM框架(Spring+SpringMVC+MyBatis(MyBatis-Plus))是目前最常用的,此次仍然是m ...

  6. spring 4 + jpa(hibernate 3/4) + spring mvc 多数据源配置

    先从persistence.xml开始: <?xml version=”1.0″ encoding=”UTF-8″?><persistence version=”2.1″ xmlns ...

  7. SSM框架的配置Spring+Springmvc +Mybatis

    ssm框架是由spring mvc +spring+mybatis组成 快速阅读 通过spring的配置文件spring.xml,在servlet中指定spring mvc的配置文件spring-mv ...

  8. hibernate+mysql的连接池配置

    1:连接池的必知概念    首先,我们还是老套的讲讲连接池的基本概念,概念理解清楚了,我们也知道后面是怎么回事了. 以前我们程序连接数据库的时候,每一次连接数据库都要一个连接,用完后再释放.如果频繁的 ...

  9. 【JAVA】Spring 数据源配置整理

            在Spring中,不但可以通过JNDI获取应用服务器的数据源,也可以直接在Spring容器中配置数据源,此外,还可以通过代码的方式创建一个数据源,以便进行无依赖的单元测试. 配置数据源 ...

随机推荐

  1. Kotlin Reference (九) Properties and Fields

    most from reference 声明属性 Koltin的类都有属性,这些属性可以声明为可变的,使用var关键字或用val关键字生声明不可变属性. class Address { var nam ...

  2. 接口测试HttpClient实践20150925

    用了工具做接口测试,但是对于加密数据和结果的比对,以及批量数据读取,回头还是觉得代码来更方便灵活,从excle中读取数据,构成参数,发请求,并获取返回结果和预期值比较,并将结果输出程报告,可以深入做成 ...

  3. Centos 中扩展 软件源 的安装 之 Remi ( 为yum 扩展软件源 )

    平时一般都是使用Ubuntu的,最近用起来Centos 发现软件安装方便不是很方便,   在安装过程中接触到了这么一个概念,  就是为yum 安装 扩展源,  这里下面要说的就是其中的  Remi  ...

  4. 一台 linux 主机装两个mysql

    启动 3306 nohup /usr/local/mysql5.1.7/bin/mysqld_safe & 启动 3307/usr/local/mysql/bin/mysqld --defau ...

  5. Codeforces 158B:Taxi

    B. Taxi time limit per test 3 seconds memory limit per test 256 megabytes input standard input outpu ...

  6. .NET CORE微服务实践

    .NET CORE微服务实践 https://www.cnblogs.com/zengqinglei/p/9570343.html .NET CORE 实践部署架构图 实践源码:https://git ...

  7. 堆排序(C语言实现)

    一.堆的概念 所谓堆,它是一个数组,也能够被看成一个近似的全然二叉树.树上每一个结点相应数组的一个元素.二叉堆分为二种:最大堆和最小堆.本文主要介绍最大堆,最小堆类似.最大堆的特点:对于随意某个结点, ...

  8. 使用IAR编译STM8S 怎样生产烧录文件

      IAR编译后能够生成的烧录文件格式有4中,例如以下 第一种是Motorola,其生成文件和STVD生成烧录文件.s19格式一样的,即能够通用 另外一种是16进制,keil等等常都用到的. 第三种是 ...

  9. 3——FFMPEG之解复用器-----AVInputFormat(转)

    1. 数据结构: AVInputFormat为FFMPEG的解复用器对象,通过调用av_register_all(),FFMPEG所有的解复用器保存在以first_iformat为链表头的链表中,且还 ...

  10. settimeout()在IE8下参数无效问题解决方法

    遇到这个问题,setTimeout(Scroll(),3000); 这种写法在IE8 下 不能够执行,提示参数无效, setTimeout(function(){Scroll()},3000);这种方 ...