读书人

spring3+hibernate4+maven+junit 多库

发布时间: 2013-08-10 21:14:06 作者: rapoo

spring3+hibernate4+maven+junit 多库/多数据源实现
1.核心思想:
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.这样实现的缺点,暂时还未想到。欢迎网友补充。
--create database-- master databasecreate database master character set `gbk` collate `gbk_chinese_ci`;-- slave databasecreate 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 datause 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.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/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.apache.org</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.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:aop="http://www.springframework.org/schema/aop"       xmlns:tx="http://www.springframework.org/schema/tx"       xmlns:context="http://www.springframework.org/schema/context"       xsi:schemaLocation="       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd       ">       <bean id="propertyConfigurer" />    <import resource="db-master.xml" />     <import resource="db-slave.xml" />            </beans>


<beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:aop="http://www.springframework.org/schema/aop"       xmlns:tx="http://www.springframework.org/schema/tx"       xmlns:context="http://www.springframework.org/schema/context"       xsi:schemaLocation="       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd       ">           <!-- Hibernate Data Source -->    <bean id="masterDataSource" 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" name="code"><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:aop="http://www.springframework.org/schema/aop"       xmlns:tx="http://www.springframework.org/schema/tx"       xmlns:context="http://www.springframework.org/schema/context"       xsi:schemaLocation="       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd       ">    <!-- Hibernate Data Source -->    <bean id="slaveDataSource" 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" name="code">hibernate.master.dialect=org.hibernate.dialect.MySQLInnoDBDialectconnection.master.driver_class=com.mysql.jdbc.Driverconnection.master.url=jdbc:mysql://localhost:3306/master?useUnicode=true&characterEncoding=gbkconnection.master.username=rootconnection.master.password=这里是你连库的密码


hibernate.slave.dialect=org.hibernate.dialect.MySQLInnoDBDialectconnection.slave.driver_class=com.mysql.jdbc.Driverconnection.slave.url=jdbc:mysql://localhost:3306/slave?useUnicode=true&characterEncoding=gbkconnection.slave.username=rootconnection.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>{//根据网友建议其实也可以在dao中直接注入 sessionFactory 像这样//  @Autowired//  @Qualifier("masterSessionFactory")//  private SessionFactory sessionFactory;}


注意UserinfoDao的包路径是 package com.xkorey.db.slave.dao;
@Repository("UserinfoDao")public class UserinfoDao extends GenericDao<Userinfo>{// 根据网友建议实也可以在dao中直接注入 sessionFactory 像这样//    @Autowired//    @Qualifier("slaveSessionFactory")//    private SessionFactory sessionFactory;}


@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=?28Hibernate: 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 1 楼 追求技术 2013-08-05 你这是在提前已经知道了该使用哪个数据源的情况下使用多数据源,个人觉得完全没有必要再在代码里面通过class name来区别该使用哪个数据源。比如你把所有使用master数据源的dao都放到master包下面,既然你已经知道了某一dao是使用的master数据源,那么你完全可以在这个代码中直接注入一个master数据源对应的sessionFactory。 2 楼 xkorey 2013-08-05 追求技术 写道你这是在提前已经知道了该使用哪个数据源的情况下使用多数据源,个人觉得完全没有必要再在代码里面通过class name来区别该使用哪个数据源。比如你把所有使用master数据源的dao都放到master包下面,既然你已经知道了某一dao是使用的master数据源,那么你完全可以在这个代码中直接注入一个master数据源对应的sessionFactory。
你说的有道理。这样做的话,那分包也就不用了。直接注入就可以了。
3 楼 youjianbo_han_87 2013-08-05 追求技术 写道你这是在提前已经知道了该使用哪个数据源的情况下使用多数据源,个人觉得完全没有必要再在代码里面通过class name来区别该使用哪个数据源。比如你把所有使用master数据源的dao都放到master包下面,既然你已经知道了某一dao是使用的master数据源,那么你完全可以在这个代码中直接注入一个master数据源对应的sessionFactory。
对的,对于读取的,全部从slave中读,插入和更新,都往主库里面操作。

读书人网 >开源软件

热点推荐