在实际项目中,怎么样搭建多数据源?
- 举个例子,两个数据源。test001、test002
分包结构
cn.lvhaosir.test001 访问test001数据库
cn.lvhaosir.test002 访问test002数据库
多数据源配置
- 注意点:多个数据源要配置一个默认的数据源。加上 @Primary 注解
报错信息:
expected single matching bean but found 2: test01DataSource,test02DataSource
代表项目中有两个数据源。test01DataSource,test02DataSource。它不知道该选择哪一个。要设置一个默认的、
解决方法:在其中一个数据源上,设置一个为默认的。加上 @Primary
首先,创建数据库信息
创建两个数据库: test01、test02
两个库下都只有一张表:
CREATE TABLE users
(
id INT AUTO_INCREMENT PRIMARY KEY ,
NAME VARCHAR(30) ,
age INT
)
application.properties 配置
### test01 datasource
spring.datasource.test01.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.test01.url=jdbc:mysql://localhost:3306/test01
spring.datasource.test01.username=root
spring.datasource.test01.password=123
### test02 datasource
spring.datasource.test02.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.test02.url=jdbc:mysql://localhost:3306/test02
spring.datasource.test02.username=root
spring.datasource.test02.password=123
包结构
cn.lvhaosir
datasource
entity
test01
controller
dao
test02
controller
dao
pom.xml 依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<dependencies>
<!-- SpringBoot 核心组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
</dependencies>
datasource 包 下的 DataSource1Config.java
package cn.lvhaosir.datasource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration // 注册到springboot容器中
@MapperScan(basePackages = "cn.lvhaosir.test01", sqlSessionFactoryRef = "test01SqlSessionFactory")
public class DataSource1Config {
/**
* 配置 test01 数据库
* @return
*/
@Bean(name = "test01DataSource")
@ConfigurationProperties(prefix = "spring.datasource.test01")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
/**
* test01 SQL 会话工厂
* @param dataSource
* @return
* @throws Exception
*/
@Bean(name = "test01SqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test01DataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// mybatis写配置文件
// bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
return bean.getObject();
}
/**
* test01 事务管理
* @param dataSource
* @return
*/
@Bean(name = "test01TransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("test01DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "test01SqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(
@Qualifier("test01SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
datasource 包 下的 DataSource2Config.java
package cn.lvhaosir.datasource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration // 注册到springboot容器中
@MapperScan(basePackages = "cn.lvhaosir.test02", sqlSessionFactoryRef = "test02SqlSessionFactory")
public class DataSource2Config {
/**
* 配置 test02 数据库
* @return
*/
@Bean(name = "test02DataSource")
@ConfigurationProperties(prefix = "spring.datasource.test02")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
/**
* test02 SQL 会话工厂
* @param dataSource
* @return
* @throws Exception
*/
@Bean(name = "test02SqlSessionFactory")
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test02DataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// mybatis写配置文件
// bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
return bean.getObject();
}
/**
* test02 事务管理
* @param dataSource
* @return
*/
@Bean(name = "test02TransactionManager")
public DataSourceTransactionManager testTransactionManager(@Qualifier("test02DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "test02SqlSessionTemplate")
public SqlSessionTemplate testSqlSessionTemplate(
@Qualifier("test02SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
entity包下的 User.java 实体类
package cn.lvhaosir.entity;
/**
* Created by lvhaosir on 2018/8/5.
*/
public class User {
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
test01/dao 下的 UserMapperTest01.java
package cn.lvhaosir.test01.dao;
import cn.lvhaosir.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapperTest01 {
@Select("SELECT * FROM USERS WHERE NAME = #{name}")
User findByName(@Param("name") String name);
@Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
test02/dao 下的 UserMapperTest02.java
package cn.lvhaosir.test02.dao;
import cn.lvhaosir.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapperTest02 {
@Select("SELECT * FROM USERS WHERE NAME = #{name}")
User findByName(@Param("name") String name);
@Insert("INSERT INTO USERS(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
test01/controller 下的 UserControllerTest01.java
package cn.lvhaosir.test01.controller;
import cn.lvhaosir.test01.dao.UserMapperTest01;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by lvhaosir on 2018/8/5.
*/
@RestController
public class UserControllerTest01 {
@Autowired
private UserMapperTest01 userMapperTest01;
@RequestMapping("/insertUserTest01")
public String insertUserTest01(String name,Integer age) {
userMapperTest01.insert(name,age);
return "Success insertUserTest01";
}
}
test02/controller 下的 UserControllerTest02.java
package cn.lvhaosir.test02.controller;
import cn.lvhaosir.test02.dao.UserMapperTest02;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserControllerTest02 {
@Autowired
private UserMapperTest02 userMapperTest02;
@RequestMapping("/insertUserTest02")
public String insertUserTest02(String name,Integer age) {
userMapperTest02.insert(name,age);
return "Success insertUserTest02";
}
}
测试
- 当请求 127.0.0.1:8080/insertUserTest01 时,附上name、age参数。会发现 test01 数据库里的 users 表的数据添加了。但 test02 中的表并没有变化。
- 当请求 127.0.0.1:8080/insertUserTest02 时,附上name、age参数。数据库 test02 中的表中添加了数据。
转载请附上原文链接,有问题请留言,谢谢支持。