---
title: "Hibernate如何配置操作多个数据库"
author: "影梦龙"
date: "2010-07-13T13:54:24Z"
tags: [".net", "Hibernate", "JDBC", "Oracle", "XML"]
categories: ["企业架构"]
slug: "hibernate"
draft: false
lastmod: "2010-07-13T14:00:18Z"
id: 711534
url: "https://yingmenglong.iteye.com/blog/711534"
---

我现在在做一个项目，需要从两个数据库实例中存取数据，在 用hibernate实现的过程中该如何配置和处理     
   
\--------------------------------------------------------------------------------     
   
1、如果一个项目要从两个乃至多个数据库实例读取数据，该如何处理？     
2、如果只有一个数据库ora，为其建立建立 ora.hbm.xml以及hibernate.properties文件，该文件中的数据库连接部分写为：   

hibernate.dialect  net.sf.hibernate.dialect.OracleDialect     
hibernate.connection.driver\_class  oracle.jdbc.driver.OracleDriver     
hibernate.connection.username  username     
hibernate.connection.password  password     
hibernate.connection.url  jdbc:oracle:thin:@local:1521:ora     
   
3、如有两个oracle数据库oraA和oraB，分 别为其建立oraA.hbm.xml和oraB.hbm.xml映射文件，这样数据库中的各个表和实体持久化类就可以映射好，但是 hibernate.properties中的数据库配置部分该如何处理呢，怎样才能同时连接上两个数据库实例呢？     
   
   
如 果用这个Configuration.configure(File  configFile)     
configFile可以是不同的配 置。     
   
通过配置configFile可以得到每个数据库的configuration，  也就是可以获得每个数据库实例的session；但是在hibernate.properties文件中怎么写数据库连接部分呢，一个数据库的时候写法 是：hibernate.connection.url  jdbc:oracle:thin:@local:1521:ora   

写 两个hibernate.properties，例如连接oraA的叫做hibernateA.properties，连接oraB的叫做 hibernateB.properties。     
   
hibernateA.properties内容如下：     
   
引 用:     
hibernate.dialect  net.sf.hibernate.dialect.OracleDialect     
hibernate.connection.driver\_class  oracle.jdbc.driver.OracleDriver     
hibernate.connection.username  username     
hibernate.connection.password  password     
hibernate.connection.url  jdbc:oracle:thin:@local:1521:oraA       
   
hibernateB.properties 内容如下：     
   
引用:     
hibernate.dialect  net.sf.hibernate.dialect.OracleDialect     
hibernate.connection.driver\_class  oracle.jdbc.driver.OracleDriver     
hibernate.connection.username  usernamet     
hibernate.connection.password  passwordt     
hibernate.connection.url  jdbc:oracle:thin:@local:1521:oraB       
   
   
程序里面：     
   
代 码:     
java代码:       
   
Configuration  conf\_oraA  =  new  Configuration("/hibernateA.properties").addClass().......;     
   
Configuration  conf\_oraB  =  new  Configuration("/hibernateB.properties").addClass().......;     
   
SessionFactory  sf\_oraA  =  conf\_oraA.buildSessionFactory();     
SessionFactory  sf\_oraB  =  conf\_oraB.buildSessionFactory();     
   
Session  s\_oraA  =  sf\_oraA.openSession();     
Session  s\_oraB  =  sf\_oraB.openSession();     
   
......   
    
   
\---------------------------------------------------------------   
   
更正一下   
方案一：   
写两个hibernate.cfg.xml   
使用数据库a的时候   
Configuration  cfg\_a=new  Configuration().configure(hibernate.cfg\_a.xml);   
使用数据库b的 时候   
Configuration  cfg\_b=new  Configuration().configure(hibernate.cfg\_b.xml);

usr/home/zk1007874/htdocs/upload\_files/images

   
方案二：   
使用一个能操作两个数据库的账号，在?.hbm.xml映射文件中的class标签中指定catalog 为数据库名