spring 配置双数据源

1.核心思想: 

思路 写道
通过spring对多数据源的管理,在dao中动态的指定相对应的datasource。


2.动态指定数据源的方法约定: 

约定 写道
不同库的dao放到对应的包下例:Master库中的dao的包路径是com.***.db.master.*。slave库的dao包的路径应是com.***.db.slave.***。
判定数据原方法 写道
判定dao类的路径是否包含master或者slave从而加载对应的数据源


3.实现代码 

Java代码   收藏代码
  1. private void fixSession(){  
  2.     String name=this.getClass().getName();  
  3.     /** 
  4.      * 如果是master 包下的dao 全部指定为 masterSessionFactory 
  5.      */  
  6.     if(name.indexOf("com.xkorey.db.master")>-1){  
  7.         sessionFactory = masterSessionFactory;  
  8.     }  
  9.     /** 
  10.      * 默认的dao是 slaveSessionFactory 下的库 
  11.      */  
  12.     else{  
  13.         sessionFactory =  slaveSessionFactory;  
  14.     }  
  15.     }  


4.这样实现的缺点,暂时还未想到。欢迎网友补充。 

缺陷 写道
未知


5.开始贴代码,附件(hsm.zip)是eclipse下的项目工程包。 
6.建库、表sql 

Hsm-db-sql.sql代码   收藏代码
  1. --create database  
  2.   
  3. -- master database  
  4. create database master character set `gbk` collate `gbk_chinese_ci`;  
  5. -- slave database  
  6. create database slave character set `gbk` collate `gbk_chinese_ci`;  
  7.   
  8.   
  9. -- create tables   
  10. use master;  
  11. create table users(  
  12. id int not null auto_increment,  
  13. name varchar(20),  
  14. age int,  
  15. primary key(id)) ENGINE = INNODB,AUTO_INCREMENT=1000;  
  16.   
  17. use slave;  
  18. create table user_info(  
  19. id int not null auto_increment,  
  20. uid int,  
  21. info varchar(20),  
  22. primary key(id)) ENGINE = INNODB,AUTO_INCREMENT=1000;  
  23.   
  24.   
  25. --insert data  
  26.   
  27. use master;  
  28. insert into users(name,age) values('xkorey',28);  
  29. use slave;  
  30. insert into user_info(uid,info) values(1000,'hello xkorey.');  


7.maven jar包依赖 pom.xml 

Pom.xml代码   收藏代码
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.   <modelVersion>4.0.0</modelVersion>  
  4.   <groupId>hsm</groupId>  
  5.   <artifactId>hsm</artifactId>  
  6.   <packaging>war</packaging>  
  7.   <version>0.0.1-SNAPSHOT</version>  
  8.   <name>hsm Maven Webapp</name>  
  9.   <url>http://maven.apache.org</url>  
  10.   <dependencies>  
  11.     <dependency>  
  12.       <groupId>junit</groupId>  
  13.       <artifactId>junit</artifactId>  
  14.       <version>3.8.1</version>  
  15.       <scope>test</scope>  
  16.     </dependency>  
  17.       
  18.         <!-- spring  -->  
  19.     <dependency>  
  20.         <groupId>org.springframework</groupId>  
  21.         <artifactId>spring-context</artifactId>  
  22.         <version>3.2.3.RELEASE</version>  
  23.     </dependency>   
  24.     <dependency>  
  25.         <groupId>org.springframework</groupId>  
  26.         <artifactId>spring-context-support</artifactId>  
  27.         <version>3.2.3.RELEASE</version>  
  28.     </dependency>  
  29.     <dependency>  
  30.         <groupId>org.springframework</groupId>  
  31.         <artifactId>spring-orm</artifactId>  
  32.         <version>3.2.3.RELEASE</version>  
  33.     </dependency>  
  34.     <dependency>  
  35.         <groupId>org.springframework</groupId>  
  36.         <artifactId>spring-webmvc</artifactId>  
  37.         <version>3.2.3.RELEASE</version>  
  38.     </dependency>  
  39.     <dependency>  
  40.         <groupId>org.springframework</groupId>  
  41.         <artifactId>spring-web</artifactId>  
  42.         <version>3.2.3.RELEASE</version>  
  43.     </dependency>  
  44.     <dependency>  
  45.         <groupId>org.springframework.security</groupId>  
  46.         <artifactId>spring-security-core</artifactId>  
  47.         <version>3.1.4.RELEASE</version>  
  48.     </dependency>  
  49.     <dependency>  
  50.         <groupId>org.springframework</groupId>  
  51.         <artifactId>spring-tx</artifactId>  
  52.         <version>3.2.3.RELEASE</version>  
  53.     </dependency>  
  54.     <dependency>  
  55.         <groupId>org.springframework</groupId>  
  56.         <artifactId>spring-test</artifactId>  
  57.         <version>3.2.1.RELEASE</version>  
  58.     </dependency>   
  59.     <dependency>  
  60.         <groupId>org.aspectj</groupId>  
  61.         <artifactId>aspectjweaver</artifactId>  
  62.         <version>1.7.2</version>  
  63.     </dependency>  
  64.               
  65.                   
  66.               
  67.               
  68.       
  69.     <!-- hibernate -->  
  70.     <dependency>  
  71.     <groupId>org.hibernate</groupId>  
  72.     <artifactId>hibernate-core</artifactId>  
  73.     <version>4.2.2.Final</version>  
  74.     </dependency>  
  75.     <dependency>  
  76.         <groupId>org.hibernate</groupId>  
  77.         <artifactId>hibernate-validator</artifactId>  
  78.         <version>4.2.0.Final</version>  
  79.     </dependency>  
  80.                   
  81.               
  82.                   
  83.                   
  84.                   
  85.       
  86.     <!-- mysql -->  
  87.     <dependency>  
  88.         <groupId>mysql</groupId>  
  89.         <artifactId>mysql-connector-java</artifactId>  
  90.         <version>5.1.25</version>  
  91.     </dependency>  
  92.       
  93.       
  94.   </dependencies>  
  95.   <build>  
  96.     <finalName>hsm</finalName>  
  97.   </build>  
  98. </project>  



8.spring配置文件 

Spring-base.xml代码   收藏代码
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.        xmlns:aop="http://www.springframework.org/schema/aop"  
  4.        xmlns:tx="http://www.springframework.org/schema/tx"  
  5.        xmlns:context="http://www.springframework.org/schema/context"  
  6.        xsi:schemaLocation="  
  7.        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  8.        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
  9.        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  
  10.        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd  
  11.        ">  
  12.          
  13.     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  14.             <property name="locations">  
  15.                 <list>  
  16.                     <value>classpath:hsm-db-master.properties</value>  
  17.                     <value>classpath:hsm-db-slave.properties</value>  
  18.                 </list>  
  19.             </property>  
  20.     </bean>  
  21.       
  22.     <context:annotation-config />  
  23.       
  24.     <context:component-scan base-package="com.xkorey.db" />  
  25.       
  26.     <import resource="db-master.xml" />   
  27.     <import resource="db-slave.xml" />  
  28.       
  29.       
  30.     </beans>  



Db-master.xml代码   收藏代码
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.        xmlns:aop="http://www.springframework.org/schema/aop"  
  4.        xmlns:tx="http://www.springframework.org/schema/tx"  
  5.        xmlns:context="http://www.springframework.org/schema/context"  
  6.        xsi:schemaLocation="  
  7.        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  8.        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
  9.        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  
  10.        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd  
  11.        ">  
  12.          
  13.     <!-- Hibernate Data Source -->  
  14.     <bean id="masterDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  15.         <property name="driverClassName"><value>${connection.master.driver_class}</value></property>  
  16.         <property name="url"><value>${connection.master.url}</value></property>  
  17.         <property name="username"><value>${connection.master.username}</value></property>  
  18.         <property name="password"><value>${connection.master.password}</value></property>  
  19.     </bean>      
  20.      <!-- Hibernate Session Factory -->  
  21.     <bean id="masterSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
  22.         <property name="dataSource"><ref local="masterDataSource"/></property>  
  23.         <property name="packagesToScan" value="com.xkorey.db.master" />  
  24.         <property name="hibernateProperties">  
  25.         <props>  
  26.             <prop key="hibernate.dialect">${hibernate.master.dialect}</prop>  
  27.             <prop key="hibernate.show_sql">true</prop>  
  28.         </props>  
  29.         </property>  
  30.     </bean>   
  31.     <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) HibernateTransactionManager -->  
  32.     <tx:annotation-driven transaction-manager="masterTransactionManager"/>  
  33.     <bean id="masterTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  34.         <property name="sessionFactory"><ref local="masterSessionFactory"/></property>  
  35.     </bean>   
  36. </beans>  



Db-slave.xml代码   收藏代码
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.        xmlns:aop="http://www.springframework.org/schema/aop"  
  4.        xmlns:tx="http://www.springframework.org/schema/tx"  
  5.        xmlns:context="http://www.springframework.org/schema/context"  
  6.        xsi:schemaLocation="  
  7.        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
  8.        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd  
  9.        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd  
  10.        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd  
  11.        ">  
  12.   
  13.     <!-- Hibernate Data Source -->  
  14.     <bean id="slaveDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  15.         <property name="driverClassName"><value>${connection.slave.driver_class}</value></property>  
  16.         <property name="url"><value>${connection.slave.url}</value></property>  
  17.         <property name="username"><value>${connection.slave.username}</value></property>  
  18.         <property name="password"><value>${connection.slave.password}</value></property>  
  19.     </bean>      
  20.      <!-- Hibernate Session Factory -->  
  21.     <bean id="slaveSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">  
  22.         <property name="dataSource"><ref local="slaveDataSource"/></property>  
  23.         <property name="packagesToScan" value="com.xkorey.db.slave" />  
  24.         <property name="hibernateProperties">  
  25.         <props>  
  26.             <prop key="hibernate.dialect">${hibernate.slave.dialect}</prop>  
  27.             <prop key="hibernate.show_sql">true</prop>  
  28.         </props>  
  29.         </property>  
  30.     </bean>   
  31.     <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) HibernateTransactionManager -->  
  32.     <tx:annotation-driven transaction-manager="slaveTransactionManager"/>  
  33.     <bean id="slaveTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">  
  34.         <property name="sessionFactory"><ref local="slaveSessionFactory"/></property>  
  35.     </bean>  
  36. </beans>  



9.properties 配置文件 

Hsm-db-master.properties代码   收藏代码
  1. hibernate.master.dialect=org.hibernate.dialect.MySQLInnoDBDialect  
  2.   
  3.   
  4. connection.master.driver_class=com.mysql.jdbc.Driver  
  5. connection.master.url=jdbc:mysql://localhost:3306/master?useUnicode=true&amp;characterEncoding=gbk  
  6. connection.master.username=root  
  7. connection.master.password=这里是你连库的密码  



Hsm-db-slave.properties代码   收藏代码
  1. hibernate.slave.dialect=org.hibernate.dialect.MySQLInnoDBDialect  
  2.   
  3.   
  4. connection.slave.driver_class=com.mysql.jdbc.Driver  
  5. connection.slave.url=jdbc:mysql://localhost:3306/slave?useUnicode=true&amp;characterEncoding=gbk  
  6. connection.slave.username=root  
  7. connection.slave.password=这里是你连库的密码  



10.java 代码 略去 java bean 即spring中的model代码只贴 dao 。 

父类dao 

Genericdao代码   收藏代码
  1. public class GenericDao<T extends java.io.Serializable> {  
  2.   
  3.           
  4.     @Autowired  
  5.     @Qualifier("masterSessionFactory")  
  6.     private SessionFactory masterSessionFactory;  
  7.       
  8.       
  9.     @Autowired  
  10.     @Qualifier("slaveSessionFactory")  
  11.     private SessionFactory slaveSessionFactory;  
  12.       
  13.       
  14.     private SessionFactory sessionFactory;  
  15.       
  16.       
  17.     private void fixSession(){  
  18.     String name=this.getClass().getName();  
  19.     /**  
  20.      * 如果是master 包下的dao 全部指定为 masterSessionFactory  
  21.      */  
  22.     if(name.indexOf("com.xkorey.db.master")>-1){  
  23.         sessionFactory = masterSessionFactory;  
  24.     }  
  25.     /**  
  26.      * 默认的dao是 slaveSessionFactory 下的库  
  27.      */  
  28.     else{  
  29.         sessionFactory =  slaveSessionFactory;  
  30.     }  
  31.     }  
  32.       
  33.     public Session getSession() {  
  34.     fixSession();  
  35.         return sessionFactory.getCurrentSession();  
  36.     }  



注意UsersDao的包路径是 package com.xkorey.db.master.dao; 

Usersdao代码   收藏代码
  1. @Repository("UsersDao")  
  2. public class UsersDao extends GenericDao<Users>{  
  3. //根据网友建议其实也可以在dao中直接注入 sessionFactory 像这样  
  4. //  @Autowired  
  5. //  @Qualifier("masterSessionFactory")  
  6. //  private SessionFactory sessionFactory;  
  7. }  



注意UserinfoDao的包路径是 package com.xkorey.db.slave.dao; 

Userinfodao代码   收藏代码
  1. @Repository("UserinfoDao")  
  2. public class UserinfoDao extends GenericDao<Userinfo>{  
  3. // 根据网友建议实也可以在dao中直接注入 sessionFactory 像这样  
  4. //    @Autowired  
  5. //    @Qualifier("slaveSessionFactory")  
  6. //    private SessionFactory sessionFactory;  
  7. }  



Usersservice代码   收藏代码
  1. @Service("UsersService")  
  2. @Transactional(value="masterTransactionManager")  
  3. public class UsersService {  
  4.       
  5.     @Autowired  
  6.     @Qualifier("UsersDao")  
  7.     private UsersDao usersDao;  
  8.       
  9.     public int findUserAgeById(int id){  
  10.     Users users = (Users) usersDao.getSession().get(Users.class,id);  
  11.     return users.age;  
  12.     }  
  13. }  



Userinfoservice代码   收藏代码
  1. @Service("UserinfoService")  
  2. @Transactional(value="slaveTransactionManager")  
  3. public class UserinfoService {  
  4.   
  5.     @Autowired  
  6.     @Qualifier("UserinfoDao")  
  7.     private UserinfoDao userinfoDao;  
  8.       
  9.     public String findUserInfoById(int id){  
  10.     Userinfo userinfo = (Userinfo) userinfoDao.getSession().get(Userinfo.class,id);  
  11.     return userinfo.info;  
  12.     }  
  13. }  



11.junit 测试类 

Testdao代码   收藏代码
  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @ContextConfiguration(locations={"classpath:spring-base.xml"})  
  3. public class TestDao {  
  4.   
  5.       
  6.     @Autowired  
  7.     @Qualifier("UsersService")  
  8.     private UsersService usersService;  
  9.       
  10.     @Autowired  
  11.     @Qualifier("UserinfoService")  
  12.     private UserinfoService userinfoService;  
  13.       
  14.       
  15.     @Test  
  16.     public void testMutilDataSource(){  
  17.     int id=1000;  
  18.     System.out.println(usersService.findUserAgeById(id));  
  19.     System.out.println(userinfoService.findUserInfoById(id));  
  20.     }  
  21.       
  22.   
  23. }  



测试类运行结果: 

控制台打印代码   收藏代码
  1. Hibernate: select users0_.id as id1_0_0_, users0_.age as age2_0_0_, users0_.name as name3_0_0_ from users users0_ where users0_.id=?  
  2. 28  
  3. Hibernate: select userinfo0_.id as id1_0_0_, userinfo0_.info as info2_0_0_, userinfo0_.uid as uid3_0_0_ from user_info userinfo0_ where userinfo0_.id=?  
  4. hello xkorey.  



截图: 


12.最后贴张工程截图 

 

13.项目环境 
jdk7,eclipse Version: Kepler Release.maven:apache-maven-3.0.4

 转载于:http://xkorey.iteye.com/blog/1920059

猜你喜欢

转载自xjward.iteye.com/blog/2066143
今日推荐