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

1.核心思想:
[quote="思路"]通过spring对多数据源的管理,在dao中动态的指定相对应的datasource。[/quote]
2.动态指定数据源的方法约定:
[quote="约定"]不同库的dao放到对应的包下例:Master库中的dao的包路径是com.***.db.master.*。slave库的dao包的路径应是com.***.db.slave.***。[/quote]
[quote="判定数据原方法"]判定dao类的路径是否包含master或者slave从而加载对应的数据源[/quote]
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.这样实现的缺点,暂时还未想到。欢迎网友补充。
[quote="缺陷"]未知[/quote]
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

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
hsm
hsm
war
0.0.1-SNAPSHOT
hsm Maven Webapp
http://maven.apache.org


junit
junit
3.8.1
test




org.springframework
spring-context
3.2.3.RELEASE


org.springframework
spring-context-support
3.2.3.RELEASE


org.springframework
spring-orm
3.2.3.RELEASE


org.springframework
spring-webmvc
3.2.3.RELEASE


org.springframework
spring-web
3.2.3.RELEASE


org.springframework.security
spring-security-core
3.1.4.RELEASE


org.springframework
spring-tx
3.2.3.RELEASE


org.springframework
spring-test
3.2.1.RELEASE


org.aspectj
aspectjweaver
1.7.2








org.hibernate
hibernate-core
4.2.2.Final


org.hibernate
hibernate-validator
4.2.0.Final









mysql
mysql-connector-java
5.1.25





hsm





8.spring配置文件

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
">




classpath:hsm-db-master.properties
classpath:hsm-db-slave.properties
















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
">



${connection.master.driver_class}
${connection.master.url}
${connection.master.username}
${connection.master.password}







${hibernate.master.dialect}
true












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
">



${connection.slave.driver_class}
${connection.slave.url}
${connection.slave.username}
${connection.slave.password}







${hibernate.slave.dialect}
true











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 {


@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的包路径是 [color=red]package com.xkorey.db.master.dao;[/color]

@Repository("UsersDao")
public class UsersDao extends GenericDao{
//根据网友建议其实也可以在dao中直接注入 sessionFactory 像这样
// @Autowired
// @Qualifier("masterSessionFactory")
// private SessionFactory sessionFactory;
}


注意UserinfoDao的包路径是 [color=red]package com.xkorey.db.slave.dao;[/color]

@Repository("UserinfoDao")
public class UserinfoDao extends GenericDao{
// 根据网友建议实也可以在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=?
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.


截图:
[img]http://dl2.iteye.com/upload/attachment/0087/8467/ad7972b4-d482-3219-8b3b-6212a1fc4985.png[/img]

12.最后贴张工程截图

[img]http://dl2.iteye.com/upload/attachment/0087/8469/dfb99aaa-3300-380e-90cd-d92f128a0fc0.png[/img]

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

你可能感兴趣的:(spring3,hibernate4,mutil,spring3,hibernate4,mutil)