spring+mybatis管理多个数据源(非分布式事务)

时间:2022-12-07 02:47:57

本文通过一个demo,介绍如何使用spring+mybatis管理多个数据源,注意,本文的事务管理并非之前博文介绍的分布式事务。

这个demo将使用两个事务管理器分别管理两个数据源。对于每一个独立的事务,只涉及一个数据源。

demo功能:实现一个能依靠两个独立的事务管理器互不干涉的管理自己的数据源的web demo。

demo将实现:

1.独立地控制两个不同的数据源的事务管理器。

测试方式:restful web api

使用工具:

spring 4.1.1.RELEASE

mybatis 3.2.7

tomcat 7

在mysql中建立两个schema,分别为dev和qa。并在里面分别建立一张名字表。

schema:dev

table:namaDev

id | nameDev

scheme:qa

table:nameQa

id  |  nameQa

对应的sql为

 CREATE SCHEMA `qa` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
CREATE SCHEMA `dev` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ; CREATE TABLE `dev`.`nameDev` (
`id` BIGINT NOT NULL AUTO_INCREMENT ,
`nameDev` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `id_UNIQUE` (`id` ASC) ); CREATE TABLE `qa`.`nameQa` (
`id` BIGINT NOT NULL AUTO_INCREMENT ,
`nameQa` VARCHAR(45) NULL ,
PRIMARY KEY (`id`) ,
UNIQUE INDEX `id_UNIQUE` (`id` ASC) );

create sql

代码分析:

本项目使用spring框架,因此首先配置相关bean

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="com.xy">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:property-placeholder location="classpath:context/database.properties"/>
<tx:annotation-driven/> <bean id="qadataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="jdbcUrl" value="${qa.db.url}"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="user" value="${qa.db.user}"></property>
<property name="password" value="${qa.db.password}"></property>
<property name="maxPoolSize" value="20"></property>
<property name="minPoolSize" value="20"></property>
<property name="initialPoolSize" value="20"></property>
<property name="maxIdleTime" value="200"></property>
<!--<property name="numHelperThreads" value="50"></property>-->
</bean> <bean id="devdataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="jdbcUrl" value="${dev.db.url}"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="user" value="${dev.db.user}"></property>
<property name="password" value="${dev.db.password}"></property>
<property name="maxPoolSize" value="20"></property>
<property name="minPoolSize" value="20"></property>
<property name="initialPoolSize" value="20"></property>
<property name="maxIdleTime" value="200"></property>
<!--<property name="numHelperThreads" value="50"></property>-->
</bean> <bean id="qasqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="qadataSource" />
<!--<property name="mapperLocations" value="classpath*:mapper/**/*.xml" />-->
</bean> <bean id="devsqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="devdataSource" />
<!--<property name="mapperLocations" value="classpath*:mapper/**/*.xml" />-->
</bean> <bean id="qaManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="qadataSource" />
</bean> <bean id="devManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="devdataSource" />
</bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xy.dao"/>
<property name="sqlSessionFactoryBeanName" value="qasqlSessionFactory" />
</bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xy.daodev"/>
<property name="sqlSessionFactoryBeanName" value="devsqlSessionFactory" />
</bean> </beans>

其中qadataSource和devdataSource是对应两个数据库的数据源,qasqlSessionFactory和devsqlSessionFactory是mybatis的sessionfactory,两个MapperScannerConfigurer自动将不同数据源的sql语句文件与interface自动装配起来。qaManager与devManage分别管理qadataSource和devdataSource的事务,互不干涉。

Model类如下:package com.xy.model

package com.xy.model;

/**
* Created by helloworld on 2015/1/30.
*/
public class NameDev {
private long id;
private String nameDev; public long getId() {
return id;
} public void setId(long id) {
this.id = id;
} public String getNameDev() {
return nameDev;
} public void setNameDev(String nameDev) {
this.nameDev = nameDev;
}
}

NameDev

 package com.xy.model;

 /**
* Created by helloworld on 2015/1/30.
*/
public class NameQa {
private long id;
private String nameQa; public long getId() {
return id;
} public void setId(long id) {
this.id = id;
} public String getNameQa() {
return nameQa;
} public void setNameQa(String nameQa) {
this.nameQa = nameQa;
}
}

NameQa

qa数据源的mybatis mapper接口 package com.xy.dao

 package com.xy.dao;

 import com.xy.model.NameQa;

 /**
* Created by helloworld on 2015/1/30.
*/
public interface NameQaMapper {
int insert(NameQa nameQa);
}

NameQaMapper

dev数据源的mybatis mapper接口 package com.xy.devdao

 package com.xy.daodev;

 import com.xy.model.NameDev;

 /**
* Created by helloworld on 2015/1/30.
*/
public interface NameDevMapper {
int insert(NameDev nameDev);
}

NameDevMapper

处理事务的service

 package com.xy.service;

 import com.xy.dao.NameQaMapper;
import com.xy.daodev.NameDevMapper;
import com.xy.model.NameDev;
import com.xy.model.NameQa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; /**
* Created by helloworld on 2015/1/30.
*/
@Service
public class NameService {
@Autowired
NameQaMapper nameQaMapper;
@Autowired
NameDevMapper nameDevMapper; @Transactional(value = "qaManager", rollbackFor = Exception.class)
public void addQa(boolean withQaException) throws Exception {
NameQa nameQa = new NameQa();
nameQa.setNameQa("hello");
nameQaMapper.insert(nameQa); if(withQaException){
throw new Exception();
}
} @Transactional(value = "devManager", rollbackFor = Exception.class)
public void addDev(boolean withDevException) throws Exception {
NameDev nameDev = new NameDev();
nameDev.setNameDev("hello");
nameDevMapper.insert(nameDev); if(withDevException){
throw new Exception();
}
} }

NameService

controller代码

 package com.xy.controller;

 import com.xy.service.NameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; /**
* Created by helloworld on 2014/11/22.
*/
@Controller
public class mybatisController { @Autowired
NameService nameService; @RequestMapping(value = "/addName", method = RequestMethod.POST)
ModelMap addName(@RequestParam("withDevException") boolean withDevException,
@RequestParam("witQaException") boolean witQaException ) {
try {
nameService.addDev(withDevException);
} catch (Exception e) {
e.printStackTrace();
} try {
nameService.addQa(witQaException);
} catch (Exception e) {
e.printStackTrace();
}
return new ModelMap("true");
} }

controller

将项目打成war包,命名为mybatis.war部署在tomcat上。

测试:

1.POST  http://localhost:8080/mybatis/addName.json

request parameters:
withDevException=false
witQaException=false
返回:true 两个数据都添加成功

2.POST  http://localhost:8080/mybatis/addName.json

request parameters:
withDevException=false
witQaException=true
返回:true 只有dev添加成功
源码下载:http://files.cnblogs.com/files/rain-in-sun/springmvc-mybatis-multidatasource.rar