ssh连接两个数据库

来源:互联网 发布:手写识别数字 算法 编辑:程序博客网 时间:2024/05/22 00:28

spring2+struts2+hibernate3实现连接两个数据库

jdbc.properties文件,写数据库的连接信息

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/destoon?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

sql.driverClassName=net.sourceforge.jtds.jdbc.Driver
sql.url=jdbc:jtds:sqlserver://127.0.0.1:1433/business
sql.username=sa
sql.password=sa

cpool.minPoolSize=1
cpool.maxPoolSize=5
cpool.maxIdleTime=7200
cpool.maxIdleTimeExcessConnections=18000
cpool.acquireIncrement=1

applicationContext.xml文件配置两个数据源,两个SessionFactory分别对应相应的数据源

 <description>Spring公共配置</description>

 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
  <property name="ignoreResourceNotFound" value="true" />
  <property name="locations">
   <list>
    <value>classpath*:/jdbc.properties</value>
   </list>
  </property>
 </bean>  
 <bean id="sqlDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  <property name="driverClass" value="${sql.driverClassName}" />
  <property name="jdbcUrl" value="${sql.url}" />
  <property name="user" value="${sql.username}" />
  <property name="password" value="${sql.password}" />
  <property name="autoCommitOnClose" value="true"/>
  <property name="initialPoolSize" value="${cpool.minPoolSize}"/>
  <property name="minPoolSize" value="${cpool.minPoolSize}"/>
  <property name="maxPoolSize" value="${cpool.maxPoolSize}"/>
  <property name="maxIdleTime" value="${cpool.maxIdleTime}"/>
  <property name="acquireIncrement" value="${cpool.acquireIncrement}"/>
  <property name="maxIdleTimeExcessConnections" value="${cpool.maxIdleTimeExcessConnections}"/>
 </bean> 


 <!-- SqlServer Hibernate配置 -->
 <bean id="sqlSessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource" ref="sqlDataSource" />
  <property name="namingStrategy">
   <bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
  </property> 
  <!-- --> 
  <property name="mappingLocations">
   <list>
    <value>classpath*:/com/search/bean/*.hbm.xml</value>
     </list>
  </property>

  <property name="hibernateProperties">
   <value>
   hibernate.dialect=org.hibernate.dialect.SQLServerDialect
   hibernate.show_sql=true 
   hibernate.format_sql=false
   hibernate.query.substitutions=true 1, false 0
   hibernate.jdbc.batch_size=20
   hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
   hibernate.cache.provider_configuration_file_resource_path=/ehcache-hibernate.xml
   </value>  
  </property>

 </bean>
 
 <!-- Mysql数据源配置-->
 <bean id="mysqlDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  <property name="driverClass" value="${jdbc.driverClassName}" />
  <property name="jdbcUrl" value="${jdbc.url}" />
  <property name="user" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />
  <property name="autoCommitOnClose" value="true"/>
  <property name="initialPoolSize" value="${cpool.minPoolSize}"/>
  <property name="minPoolSize" value="${cpool.minPoolSize}"/>
  <property name="maxPoolSize" value="${cpool.maxPoolSize}"/>
  <property name="maxIdleTime" value="${cpool.maxIdleTime}"/>
  <property name="acquireIncrement" value="${cpool.acquireIncrement}"/>
  <property name="maxIdleTimeExcessConnections" value="${cpool.maxIdleTimeExcessConnections}"/>
 </bean> 
  
   <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource" ref="mysqlDataSource" />
  <property name="namingStrategy">
   <bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
  </property> 
  <property name="mappingLocations">
   <list>
    <value>classpath*:/com/search/bean/*.hbm.xml</value>
     </list>
  </property>

  <property name="hibernateProperties">
   <value>
   hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
   hibernate.show_sql=true 
   hibernate.format_sql=false
   hibernate.query.substitutions=true 1, false 0
   hibernate.jdbc.batch_size=20
   hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider
   hibernate.cache.provider_configuration_file_resource_path=/ehcache-hibernate.xml
   </value>  
  </property>
 </bean>

DAO类,提供两个sessionFactory,根据数据库关键字而连接不同的数据库

@Repository

public abstract class BaseDaoImpl<T extends Serializable> implements BaseDao<T>  {

 protected Logger log = LoggerFactory.getLogger(getClass());
 public static final String SQLSERVER="sqlserver";
 public static final String MYSQL="mysql";
 protected static SessionFactory sessionFactory;

 @Autowired
 @Resource(name="sessionFactory")
 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 public Session getSession() {
  return sessionFactory.getCurrentSession();
 }
 protected static SessionFactory sqlSessionFactory;
 @Autowired
 @Resource(name="sqlSessionFactory")
 public  void setSqlSessionFactory(SessionFactory sqlSessionFactory) {
  this.sqlSessionFactory = sqlSessionFactory;
 }
 public  Session getSqlSession(String database) {
  if (database.equals(SQLSERVER)) {
   return sqlSessionFactory.getCurrentSession();
  }else if (database.equals(MYSQL)) {
   return sessionFactory.getCurrentSession();
  }
  return null; 
 }
 @SuppressWarnings("unchecked")
 public List searchListBySQL(String sql,String database) {
  return getSqlSession(database).createSQLQuery(sql).list();
 }

}

DAO实现类

@Repository
public class ProductDaoImpl  extends JeeCoreDaoImpl<Product> implements ProductDao { 

public List getAllProducts(){
  String hql="select * from table;

  return searchListBySQL(hql,"mysql");  
 } 

}




第二种方法

一、(在src下)写两个Hibernate.cfg.xml文件: 
            hbn-mysql.cfg.xml和hbn-sqlserver.cfg.xml 
二、分别解析上面的两个.cfg.xml文件建两个sessionFactory, 
三、使用session时哪个sessionFactory打开的session就能访问哪个数据库。
 

详细步骤:----------------------------------------- 
一、(在src下)建两个Hibernate.cfg.xml文件 

(1.)hbn-mysql.cfg.xml的内容: 

Java代码  收藏代码
  1. <?xml version='1.0' encoding='utf-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">  
  4. <!--hibernate配置文件,定义所使用的MySQL数据库的配置信息 -->  
  5. <hibernate-configuration>  
  6. <session-factory>  
  7. <property name="myeclipse.connection.profile">mysql</property>  
  8. <property name="connection.url">jdbc:mysql://localhost:3306/dataSource?characterEncoding=utf-8</property>  
  9. <property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.username">root</property>  
  10. <property name="connection.password">password</property>  
  11. <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
  12. <mapping  
  13.    resource="com/fourstar/starTransport/daomain/orderIdStatus.hbm.xml" />  
  14. <mapping  
  15.    resource="com/fourstar/starTransport/daomain/freightCompany.hbm.xml" />  
  16. </session-factory>  
  17. </hibernate-configuration>  

(2.)hbn-sqlserver.cfg.xml的内容: 

Java代码  收藏代码
  1. <?xml version="1.0"?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3. "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4. "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5. <hibernate-configuration>  
  6. <session-factory>  
  7. <property name="show_sql">true</property>  
  8. <property name="connection.driver_class">  
  9.    com.microsoft.sqlserver.jdbc.SQLServerDriver  
  10. </property>  
  11. <property name="connection.url">  
  12.    jdbc:sqlserver://192.168.2.16:1433; DatabaseName=DB  
  13. </property>  
  14. <property name="connection.username">root</property>  
  15. <property name="connection.password">password</property>  
  16. <property name="connection.isolation">2</property>  
  17. <property name="dialect">  
  18.    org.hibernate.dialect.SQLServerDialect  
  19. </property>  
  20. <mapping  
  21.    resource="com/fourstar/starTransport/daomain/transactions.hbm.xml" />  
  22.    <mapping  
  23.    resource="com/fourstar/starTransport/daomain/transactionDetail.hbm.xml" />  
  24. </session-factory>  
  25. </hibernate-configuration>  


二、建一个类(HbnUtil)用于连接数据库(用于创建sessionFactory和openSession()静态方法) 

Java代码  收藏代码
  1. package com.fourstar.starTransport.dao.util;  
  2.   
  3. import org.hibernate.Session;  
  4. import org.hibernate.SessionFactory;  
  5. import org.hibernate.cfg.Configuration;  
  6.   
  7. public class HbnUtil {// 根据hibernate.cfg.xml创建一个静态sessionFactory  
  8.   
  9. private static SessionFactory sf;  
  10. private static SessionFactory MSsf;  
  11. static {  
  12.    sf = new Configuration().configure("/hbn-sqlserver.cfg.xml")  
  13.      .buildSessionFactory();  
  14.    MSsf = new Configuration().configure("/hbn-mysql.cfg.xml")  
  15.    .buildSessionFactory();  
  16. }  
  17.   
  18. /**根据DBName判断调用哪个sessionFactory的openSession()方法*/  
  19. public static Session getSessionByDB(String DBName) {  
  20.    Session s = null;  
  21.   
  22.    if (DBName == "mysql") {  
  23.     if (!MSsf.isClosed())  
  24.      s = MSsf.openSession();  
  25.    } else if (DBName == "sqlserver") {  
  26.     if (!sf.isClosed())  
  27.      s = sf.openSession();  
  28.    } else {  
  29.     System.out.println("错误的 DBName!");  
  30.    }  
  31.    return s;  
  32. }  
  33. /**根据DBName判断调用哪个sessionFactory的close()方法*/  
  34. public static void closeSessionFactoryByDB(String DBName) {  
  35.    if (DBName == "mysql") {  
  36.     if (!MSsf.isClosed()) {  
  37.      MSsf.close();  
  38.     }  
  39.    } else if (DBName == "sqlserver") {  
  40.     if (!sf.isClosed()) {  
  41.      sf.close();  
  42.     }  
  43.    } else {  
  44.     System.out.println("错误的 DBName!");  
  45.    }  
  46. }  
  47. }  

三、测试:使用getSessionByDB(String DBName)获得不同数据库的session 

Java代码  收藏代码
  1. package com.fourstar.starTransport.dao.util;  
  2.   
  3. import org.hibernate.HibernateException;  
  4. import org.hibernate.Query;  
  5. import org.hibernate.Session;  
  6.   
  7. public class Test1{  
  8. public static void main(String[] args) {  
  9.    String DBName = "mysql";  
  10. // String DBName = "sqlservrer";  
  11.    Session s = HbnUtil.getSessionByDB(DBName);  
  12.    try {   
  13.     String sql = " from freightCompany";  
  14.     Query query = s.createQuery(sql);   
  15.    } catch (HibernateException e) {  
  16.     e.printStackTrace();  
  17.    }finally{  
  18.     s.close();  
  19.     HbnUtil.closeSessionFactoryByDB(DBName);  
  20.    }   
  21. }  
  22. }  



———————————————————————————————————————— 

———————————————————————————————————————— 

做完这些之后我再介绍下hibernate连接两个数据库的原理:  
—————————————————————————————————————— 

一、Hibernate访问数据库时加载的过程 

            对于大多数使用Hibernate的朋友来说,通常使用一下方式来获得Configuration实例: Configuration 
            configure = new Configuration().configure(); 

            在Hibernate中,Configuration是hibernate的入口。在实例化一个Configuration的时候,Hibernate会自动在环境变量(classpath)里面查找Hibernate配置文件hibernate.properties。如果该文件存在,则将该文件的内容加载到一个Properties的实例GLOBAL_PROPERTIES里面,如果不存在,将打印信息 
            hibernate.properties not found; 

            接下来Hibernate将所有系统环境变量(System.getProperties())也添加到GLOBAL_PROPERTIES里面。如果配置文件hibernate.properties存在,系统还会进一步验证这个文件配置的有效性,对于一些已经不支持的配置参数,系统将打印出警告信息。 


            默认状态下configure()方法会自动在环境变量(classpath)下面寻找Hibernate配置文件hibernate.cfg.xml,如果该文件不存在,系统会打印如下信息并抛出HibernateException异常: 
            hibernate.cfg.xml not 
            found;如果该文件存在,configure()方法会首先访问<session-factory>,并获取该元素name的属性,如果name的属性非空,将用这个配置的值来覆盖hibernate.properties的hibernate.session_factory_name的配置的值,从这里我们可以看出,hibernate.cfg.xml里面的配置信息可以覆盖hibernate.properties的配置信息。 


            接下来configure()方法访问<session-factory>的子元素,首先将使用所有的<property>元素配置的信息来覆盖hibernate.properties里面对应的配置信息。 

            然后configure()会依次访问以下几个元素的内容 
            <mapping><jcs-class-cache><jcs-collection-cache><collection-cache> 

            其中<mapping>是必不可少的,必须通过配置<mapping>,configure()才能访问到我们定义的java对象和关系数据库表的映射文件(hbm.xml),例如: 

            <mapping resource="Cat.hbm.xml"/> 

            这样configure()方法利用各种资源就创建了一个Configuration实例。对于整个项目来说,如果用一个本地线程来存放这个Configuration实例,那么整个项目只需要实例化一次Configuration对象(注:Configuration实例很花费时间),也就提高了项目的效率。 

          以上了解了解析hibernate.cfg.xml映射文件使得configuration对象的实例化的方法new Configuration().configure()。如果我们需要连接两个数据库就需要解析两个hibernate映射文件去实例化两个configuration对象,我们使用方法new Configuration().configure(“hibernate文件路径”)。然后使用configuration对象的 buildSessionFactory()方法去创建session工厂。有了session工厂就可以生产数据库操作对象session了。