spring hibernate4 mysql多数据源_spring3+hibernate4+maven+junit 多库/多数据源实现

思路 写道

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

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

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的包路径是 package com.xkorey.db.master.dao;

@Repository("UsersDao")

public class UsersDao extends GenericDao{

//根据网友建议其实也可以在dao中直接注入 sessionFactory 像这样

// @Autowired

// @Qualifier("masterSessionFactory")

// private SessionFactory sessionFactory;

}

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

@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.

截图:

184575585db942c96e5dca6fdc06a60f.png

12.最后贴张工程截图

1339e8dfe2561c74c9ab513f0917abf9.png

13.项目环境

jdk7,eclipse Version: Kepler Release.maven:apache-maven-3.0.4

7ad8835ffbedeb60237031e4c3c10caa.png

大小: 3.5 KB

3722b4e98eed739d07594365d2da113e.png

大小: 20 KB

hsm.zip (31.2 KB)

下载次数: 344

1

3

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2013-08-05 09:59

浏览 11647

评论

5 楼

chenchunhuis

2015-06-10

我们最近也在做这个事情,一楼的评论很有道理

966903dea4bcb507358d5dcce8b912e5.gif 

966903dea4bcb507358d5dcce8b912e5.gif 

966903dea4bcb507358d5dcce8b912e5.gif

4 楼

mjs123

2015-03-11

你好,我执行的时候 怎么老是报 No Session found for current thread 这个错误?

追求技术 写道

你这是在提前已经知道了该使用哪个数据源的情况下使用多数据源,个人觉得完全没有必要再在代码里面通过class name来区别该使用哪个数据源。比如你把所有使用master数据源的dao都放到master包下面,既然你已经知道了某一dao是使用的master数据源,那么你完全可以在这个代码中直接注入一个master数据源对应的sessionFactory。

对的,对于读取的,全部从slave中读,插入和更新,都往主库里面操作。

2 楼

xkorey

2013-08-05

追求技术 写道

你这是在提前已经知道了该使用哪个数据源的情况下使用多数据源,个人觉得完全没有必要再在代码里面通过class name来区别该使用哪个数据源。比如你把所有使用master数据源的dao都放到master包下面,既然你已经知道了某一dao是使用的master数据源,那么你完全可以在这个代码中直接注入一个master数据源对应的sessionFactory。

你说的有道理。这样做的话,那分包也就不用了。直接注入就可以了。

1 楼

追求技术

2013-08-05

你这是在提前已经知道了该使用哪个数据源的情况下使用多数据源,个人觉得完全没有必要再在代码里面通过class name来区别该使用哪个数据源。比如你把所有使用master数据源的dao都放到master包下面,既然你已经知道了某一dao是使用的master数据源,那么你完全可以在这个代码中直接注入一个master数据源对应的sessionFactory。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值