分享

spring3+hibernate4+maven+junit 多库/多数据源实现

 instl 2014-06-05
   1.核心思想: 2.动态指定数据源的方法约定:
不同库的dao放到对应的包下例:Master库中的dao的包路径是com.***.db.master.*。slave库的dao包的路径应是com.***.db.slave.***。

判定数据原方法 写道
判定dao类的路径是否包含master或者slave从而加载对应的数据源

3.实现代码
private void fixSession(){
  String name=this.getClass().getName();
  /**
   * 如果是master 包下的dao 全部指定为 masterSessionFactory
   */
  if(name.indexOf("com.xkorey.db.master")>-1){
      sessionFactory = masterSessionFactory;
  }
  /**
   * 默认的dao是 slaveSessionFactory 下的库
   */
  else{
      sessionFactory =  slaveSessionFactory;
  }
    }

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

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

-- master database
create database master character set `gbk` collate `gbk_chinese_ci`;
-- slave database
create database slave character set `gbk` collate `gbk_chinese_ci`;


-- create tables 
use master;
create table users(
id int not null auto_increment,
name varchar(20),
age int,
primary key(id)) ENGINE = INNODB,AUTO_INCREMENT=1000;

use slave;
create table user_info(
id int not null auto_increment,
uid int,
info varchar(20),
primary key(id)) ENGINE = INNODB,AUTO_INCREMENT=1000;


--insert data

use master;
insert into users(name,age) values('xkorey',28);
use slave;
insert into user_info(uid,info) values(1000,'hello xkorey.');

7.maven jar包依赖 pom.xml
<project xmlns="http://maven./POM/4.0.0" xmlns:xsi="http://www./2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven./POM/4.0.0 http://maven./maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>hsm</groupId>
  <artifactId>hsm</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>hsm Maven Webapp</name>
  <url>http://maven.</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
    	<!-- spring  -->
    <dependency>
   	<groupId>org.springframework</groupId>
   	<artifactId>spring-context</artifactId>
   	<version>3.2.3.RELEASE</version>
  </dependency> 
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>3.2.3.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.3.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.2.3.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>3.2.3.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>3.1.4.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>3.2.3.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.2.1.RELEASE</version>
  </dependency>	
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.7.2</version>
  </dependency>
            
              
            
            
  
  <!-- hibernate -->
  <dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>4.2.2.Final</version>
  </dependency>
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>4.2.0.Final</version>
  </dependency>
              
            
              
              
              
  
  <!-- mysql -->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.25</version>
  </dependency>
    
    
  </dependencies>
  <build>
    <finalName>hsm</finalName>
  </build>
</project>

8.spring配置文件
<beans xmlns="http://www./schema/beans"
       xmlns:xsi="http://www./2001/XMLSchema-instance"
       xmlns:aop="http://www./schema/aop"
       xmlns:tx="http://www./schema/tx"
       xmlns:context="http://www./schema/context"
       xsi:schemaLocation="
       http://www./schema/beans http://www./schema/beans/spring-beans-3.2.xsd
       http://www./schema/aop http://www./schema/aop/spring-aop-3.2.xsd
       http://www./schema/tx http://www./schema/tx/spring-tx-3.2.xsd
       http://www./schema/context http://www./schema/context/spring-context-3.2.xsd
       ">
       
  <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
          <property name="locations">
              <list>
                  <value>classpath:hsm-db-master.properties</value>
                  <value>classpath:hsm-db-slave.properties</value>
              </list>
          </property>
  </bean>
  
  <context:annotation-config />
  
  <context:component-scan base-package="com.xkorey.db" />
  
    <import resource="db-master.xml" /> 
    <import resource="db-slave.xml" />
    
    
    </beans>

<beans xmlns="http://www./schema/beans"
       xmlns:xsi="http://www./2001/XMLSchema-instance"
       xmlns:aop="http://www./schema/aop"
       xmlns:tx="http://www./schema/tx"
       xmlns:context="http://www./schema/context"
       xsi:schemaLocation="
       http://www./schema/beans http://www./schema/beans/spring-beans-3.2.xsd
       http://www./schema/aop http://www./schema/aop/spring-aop-3.2.xsd
       http://www./schema/tx http://www./schema/tx/spring-tx-3.2.xsd
       http://www./schema/context http://www./schema/context/spring-context-3.2.xsd
       ">
       
    <!-- Hibernate Data Source -->
    <bean id="masterDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"><value>${connection.master.driver_class}</value></property>
        <property name="url"><value>${connection.master.url}</value></property>
        <property name="username"><value>${connection.master.username}</value></property>
        <property name="password"><value>${connection.master.password}</value></property>
    </bean>    
     <!-- Hibernate Session Factory -->
    <bean id="masterSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource"><ref local="masterDataSource"/></property>
        <property name="packagesToScan" value="com.xkorey.db.master" />
        <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.master.dialect}</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
        </property>
    </bean> 
    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) HibernateTransactionManager -->
    <tx:annotation-driven transaction-manager="masterTransactionManager"/>
    <bean id="masterTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory"><ref local="masterSessionFactory"/></property>
    </bean> 
</beans>

<beans xmlns="http://www./schema/beans"
       xmlns:xsi="http://www./2001/XMLSchema-instance"
       xmlns:aop="http://www./schema/aop"
       xmlns:tx="http://www./schema/tx"
       xmlns:context="http://www./schema/context"
       xsi:schemaLocation="
       http://www./schema/beans http://www./schema/beans/spring-beans-3.2.xsd
       http://www./schema/aop http://www./schema/aop/spring-aop-3.2.xsd
       http://www./schema/tx http://www./schema/tx/spring-tx-3.2.xsd
       http://www./schema/context http://www./schema/context/spring-context-3.2.xsd
       ">

    <!-- Hibernate Data Source -->
    <bean id="slaveDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName"><value>${connection.slave.driver_class}</value></property>
        <property name="url"><value>${connection.slave.url}</value></property>
        <property name="username"><value>${connection.slave.username}</value></property>
        <property name="password"><value>${connection.slave.password}</value></property>
    </bean>    
     <!-- Hibernate Session Factory -->
    <bean id="slaveSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource"><ref local="slaveDataSource"/></property>
        <property name="packagesToScan" value="com.xkorey.db.slave" />
        <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.slave.dialect}</prop>
            <prop key="hibernate.show_sql">true</prop>
        </props>
        </property>
    </bean> 
    <!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) HibernateTransactionManager -->
    <tx:annotation-driven transaction-manager="slaveTransactionManager"/>
    <bean id="slaveTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory"><ref local="slaveSessionFactory"/></property>
    </bean>
</beans>

9.properties 配置文件
hibernate.master.dialect=org.hibernate.dialect.MySQLInnoDBDialect


connection.master.driver_class=com.mysql.jdbc.Driver
connection.master.url=jdbc:mysql://localhost:3306/master?useUnicode=true&characterEncoding=gbk
connection.master.username=root
connection.master.password=这里是你连库的密码

hibernate.slave.dialect=org.hibernate.dialect.MySQLInnoDBDialect


connection.slave.driver_class=com.mysql.jdbc.Driver
connection.slave.url=jdbc:mysql://localhost:3306/slave?useUnicode=true&characterEncoding=gbk
connection.slave.username=root
connection.slave.password=这里是你连库的密码

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

父类dao
public class GenericDao<T extends java.io.Serializable> {

    	
    @Autowired
    @Qualifier("masterSessionFactory")
    private SessionFactory masterSessionFactory;
    
    
    @Autowired
    @Qualifier("slaveSessionFactory")
    private SessionFactory slaveSessionFactory;
    
    
    private SessionFactory sessionFactory;
    
    
    private void fixSession(){
  String name=this.getClass().getName();
  /**
   * 如果是master 包下的dao 全部指定为 masterSessionFactory
   */
  if(name.indexOf("com.xkorey.db.master")>-1){
      sessionFactory = masterSessionFactory;
  }
  /**
   * 默认的dao是 slaveSessionFactory 下的库
   */
  else{
      sessionFactory =  slaveSessionFactory;
  }
    }
    
    public Session getSession() {
  fixSession();
        return sessionFactory.getCurrentSession();
    }

注意UsersDao的包路径是 package com.xkorey.db.master.dao;
@Repository("UsersDao")
public class UsersDao extends GenericDao<Users>{}

注意UserinfoDao的包路径是 package com.xkorey.db.slave.dao;
@Repository("UserinfoDao")
public class UserinfoDao extends GenericDao<Userinfo>{}

@Service("UsersService")
@Transactional(value="masterTransactionManager")
public class UsersService {
    
    @Autowired
    @Qualifier("UsersDao")
    private UsersDao usersDao;
    
    public int findUserAgeById(int id){
  Users users = (Users) usersDao.getSession().get(Users.class,id);
  return users.age;
    }
}

@Service("UserinfoService")
@Transactional(value="slaveTransactionManager")
public class UserinfoService {

    @Autowired
    @Qualifier("UserinfoDao")
    private UserinfoDao userinfoDao;
    
    public String findUserInfoById(int id){
  Userinfo userinfo = (Userinfo) userinfoDao.getSession().get(Userinfo.class,id);
  return userinfo.info;
    }
}

11.junit 测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-base.xml"})
public class TestDao {

    
    @Autowired
    @Qualifier("UsersService")
    private UsersService usersService;
    
    @Autowired
    @Qualifier("UserinfoService")
    private UserinfoService userinfoService;
    
    
    @Test
    public void testMutilDataSource(){
  int id=1000;
  System.out.println(usersService.findUserAgeById(id));
  System.out.println(userinfoService.findUserInfoById(id));
    }
    

}

测试类运行结果:
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=?
28
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=?
hello xkorey.

截图:

12.最后贴张工程截图


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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约