首先我们建立两个数据库(可以不在同一台电脑上):
multiple_order :
DROP DATABASE IF EXISTS `multiple_order`;
CREATE DATABASE `multiple_order`;
USE `multiple_order`;
CREATE TABLE `order` (
`order_id` BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '订单id',
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '用户id',
`cost` DECIMAL(13, 2) COMMENT '订单费用'
) COMMENT '订单表';
multiple_user :
DROP DATABASE IF EXISTS `multiple_user`;
CREATE DATABASE `multiple_user`;
USE `multiple_user`;
CREATE TABLE `user` (
`user_id` BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT COMMENT '用户id',
`username` VARCHAR(50) NOT NULL COMMENT '用户名',
`age` TINYINT UNSIGNED COMMENT '年龄'
) COMMENT '用户表';
然后创建一个maven项目,其中 pom.xml 文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.9.RELEASE</version>
</parent>
<groupId>love.xiaohh.datasource</groupId>
<artifactId>multiple-datasources</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
在 application.yml 中需要配置两个数据源:
spring:
datasource:
user:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/multiple_user?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: xiaohh
order:
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://127.0.0.1:3306/multiple_order?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: xiaohh
mybatis:
mapper-locations: classpath:mapper/**/*Mapper.xml
然后我们定义一个配置类 DataSourseConfig 用于配置多数据源,首先是申明数据源,按照 application.yml 当中的配置定义两个数据源,注意当中的DataSource 是 javax.sql.DataSource :
@Primary
@Bean("user")
@ConfigurationProperties(prefix = "spring.datasource.user")
public DataSource user() {
return DataSourceBuilder.create().build();
}
@Bean("order")
@ConfigurationProperties(prefix = "spring.datasource.order")
public DataSource order() {
return DataSourceBuilder.create().build();
}
然后创建 SqlSessionFactory :
@Primary
@Bean("userSqlSessionFactory")
public SqlSessionFactory userSqlSessionFactory(@Qualifier("user") DataSource user) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(user);
factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/user/*.xml"));
return factory.getObject();
}
@Bean("orderSqlSessionFactory")
public SqlSessionFactory orderSqlSessionFactory(@Qualifier("order") DataSource order) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(order);
factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/order/*.xml"));
return factory.getObject();
}
最后声明两个 SqlSessionTemplate :
@Primary
@Bean("userSqlSessionTemplate")
public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory") SqlSessionFactory userSqlSessionFactory) {
return new SqlSessionTemplate(userSqlSessionFactory);
}
@Bean("orderSqlSessionTemplate")
public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory orderSqlSessionFactory) {
return new SqlSessionTemplate(orderSqlSessionFactory);
}
最后别忘了在配置类上加上一个注解,用于声明哪些Mapper文件用哪些注解:
@Configuration
@MapperScans({
@MapperScan(basePackages = "love.xiaohh.datasource.mapper.user", sqlSessionTemplateRef = "userSqlSessionTemplate"),
@MapperScan(basePackages = "love.xiaohh.datasource.mapper.order", sqlSessionTemplateRef = "orderSqlSessionTemplate")
})
完整的 DataSourceConfig 类的代码:
package love.xiaohh.datasource.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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 javax.sql.DataSource;
@Configuration
@MapperScans({
@MapperScan(basePackages = "love.xiaohh.datasource.mapper.user", sqlSessionTemplateRef = "userSqlSessionTemplate"),
@MapperScan(basePackages = "love.xiaohh.datasource.mapper.order", sqlSessionTemplateRef = "orderSqlSessionTemplate")
})
public class DataSourceConfig {
@Primary
@Bean("user")
@ConfigurationProperties(prefix = "spring.datasource.user")
public DataSource user() {
return DataSourceBuilder.create().build();
}
@Bean("order")
@ConfigurationProperties(prefix = "spring.datasource.order")
public DataSource order() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean("userSqlSessionFactory")
public SqlSessionFactory userSqlSessionFactory(@Qualifier("user") DataSource user) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(user);
factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/user/*.xml"));
return factory.getObject();
}
@Bean("orderSqlSessionFactory")
public SqlSessionFactory orderSqlSessionFactory(@Qualifier("order") DataSource order) throws Exception {
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
factory.setDataSource(order);
factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/order/*.xml"));
return factory.getObject();
}
@Primary
@Bean("userSqlSessionTemplate")
public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory") SqlSessionFactory userSqlSessionFactory) {
return new SqlSessionTemplate(userSqlSessionFactory);
}
@Bean("orderSqlSessionTemplate")
public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory orderSqlSessionFactory) {
return new SqlSessionTemplate(orderSqlSessionFactory);
}
}
然后按照注解上面定义的包创建两个 Mapper 接口
OrderMapper :
package love.xiaohh.datasource.mapper.order;
import love.xiaohh.datasource.entities.order.Order;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface OrderMapper {
int insertOrder(Order order);
List<Order> selectOrder(Order order);
}
UserMapper :
package love.xiaohh.datasource.mapper.user;
import love.xiaohh.datasource.entities.user.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
int insertUser(User user);
List<User> selectUser(User user);
}
之后我会将代码提交到 gitee,所以 Mapper.xml、Controller、Service 代码在此处省略,然后我们新增几条用户数据:
查询一下:
同时订单数据库:
查询:
然后在数据库当中查看是否是发送到不同的数据库:
可以确定,确实是存入了两个数据库。好了下课 代码仓库 :https://gitee.com/xiaohha/multiple-datasources
|