创建SpringBoot项目就不说了。(直接使用IDEA创建就好了)
整个目录结构如图:(不用管图中报错,项目是在另一台电脑上写的。报错是没有jar包,因为网络比较慢。)
1、主要pom.xml
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Boot Test 依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- Spring Boot Mybatis 依赖 --><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.2.0</version></dependency> <!-- MySQL 连接驱动依赖 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql-connector}</version></dependency> <!-- Druid 数据连接池依赖 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.18</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>3.8.1</version><scope>test</scope></dependency><dependency><groupId>com.microsoft.sqlserver</groupId><artifactId>mssql-jdbc</artifactId><version>7.0.0.jre8</version></dependency></dependencies>
2、在配置文件中配置多数据源application.properties
## 默认的数据源
master.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
master.datasource.username=root
master.datasource.password=admin
master.datasource.driverClassName=com.mysql.jdbc.Driver
## 另一个的数据源
cluster.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=tablename
cluster.datasource.username=sa
cluster.datasource.password=admin
cluster.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
我这配置SqlServer、MySql,如果需要连接MySql中的两个数据库。请自行更更改配置,并删除pom依赖。
3、配置mapper接口的数据源
MasterDataSourceConfig.java
package com.wzq.datasource2.config;import javax.sql.DataSource;import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;@Configuration
//扫描 Mapper 接口并容器管理
@MapperScan(basePackages = {"com.wzq.datasource2.mapper.master"}, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {// 精确到 master 目录,以便跟其他数据源隔离static final String PACKAGE = "com.wzq.datasource2.mapper.master";static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml";@Value("${master.datasource.url}")private String url;@Value("${master.datasource.username}")private String user;@Value("${master.datasource.password}")private String password;@Value("${master.datasource.driverClassName}")private String driverClass;@Primary@Bean(name = "masterDataSource")public DataSource masterDataSource() {DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName(driverClass);dataSource.setUrl(url);dataSource.setUsername(user);dataSource.setPassword(password);return dataSource;}@Bean(name = "masterTransactionManager")@Primarypublic DataSourceTransactionManager masterTransactionManager() {return new DataSourceTransactionManager(masterDataSource());}@Bean(name = "masterSqlSessionFactory")@Primarypublic SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)throws Exception {final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();sessionFactory.setDataSource(masterDataSource);sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/master/*.xml"));return sessionFactory.getObject();}
}
4、创建entity实体类
public class StuT {private static final long serialVersionUID = 1L;private Integer id;private String name;//get/set}public class Stu {private static final long serialVersionUID = 1L;private Integer id;private String name;//get/set
}
ClusterDataSourceConfig.java
package com.wzq.datasource2.config;import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;import com.alibaba.druid.pool.DruidDataSource;@Configuration
//扫描 Mapper 接口并容器管理
@MapperScan(basePackages = {"com.wzq.datasource2.mapper.cluster"}, sqlSessionFactoryRef = "clusterSqlSessionFactory")
public class ClusterDataSourceConfig {// 精确到 cluster 目录,以便跟其他数据源隔离static final String PACKAGE = "com.wzq.datasource2.mapper.cluster";static final String MAPPER_LOCATION = "classpath:mapper/cluster/*.xml";@Value("${cluster.datasource.url}")private String url;@Value("${cluster.datasource.username}")private String user;@Value("${cluster.datasource.password}")private String password;@Value("${cluster.datasource.driverClassName}")private String driverClass;@Bean(name = "clusterDataSource")public DataSource clusterDataSource() {DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName(driverClass);dataSource.setUrl(url);dataSource.setUsername(user);dataSource.setPassword(password);return dataSource;}@Bean(name = "clusterTransactionManager")public DataSourceTransactionManager clusterTransactionManager() {return new DataSourceTransactionManager(clusterDataSource());}@Bean(name = "clusterSqlSessionFactory")public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource)throws Exception {final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();sessionFactory.setDataSource(clusterDataSource);sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/cluster/*.xml"));return sessionFactory.getObject();}
}
请根据实体类自行创建表
5、编写mapper层
6、Service省略,目录结构如下:
7、controller层
package com.wzq.datasource2.controller;import com.wzq.datasource2.entity.cluster.StuT;
import com.wzq.datasource2.entity.master.Stu;
import com.wzq.datasource2.service.cluster.StuTService;
import com.wzq.datasource2.service.master.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import java.util.List;@Controller
public class StuController {@Autowired@Qualifier(value = "stuServiceImpl")private StuService stuService;@Autowired@Qualifier(value = "stuTServiceImpl")private StuTService stuTService;@RequestMapping("/list")@ResponseBodypublic List<Stu> getAllStu(){return stuService.getAllStu();}@RequestMapping("/list2")@ResponseBodypublic List<StuT> getAllStuT(){return stuTService.getAllStuT();}}
总结:
1、配置多数据的目的是因为新项目需要用到老项目中的数据,而数据存放在两个不同的数据库当中,配置多数据源能很好的解决这一方面。还有一些公司进行了分库的操作,就比如一个指定增删改,一个指定查询。
2、 可能是我在配置数据源的时候使用了master或cluster,亦或者在配置mapper接口的数据源时指定的mastter或cluster,所以需要在mapperwen文件下创建master和cluster文件,以此来区分数据源的使用。
PS:报红是因为没有jar包!报红是因为没有jar包!报红是因为没有jar包!
GitHub网址:https://github.com/qz596766829/WzqRepository.git (datasoutrce2项目)
其他实现方式可以参考 SpringBoot + mybatis-plus 实现多数据源SpringBoot + mybatis-plus 实现多数据源。https://blog.csdn.net/qq_38080370/article/details/127514072 实现,通过注解的方式来指定数据源,而不用通过目录的方式来控制。