这篇文章主要为大家展示了“SpringBoot如何搭建多数据源”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“springBoot如何搭建多数据源”这篇文章吧。首先我们建立两个数据库(可以不在同一
这篇文章主要为大家展示了“SpringBoot如何搭建多数据源”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“springBoot如何搭建多数据源”这篇文章吧。
首先我们建立两个数据库(可以不在同一台电脑上):
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 '用户表';
<?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> <!-- SpringBoot的夫项目 --> <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> <!-- springMVC 相关的依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-WEB</artifactId> </dependency> <!-- Spring 健康检测模块 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- mybatis 相关依赖 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <!-- MySQL 驱动 --> <dependency> <groupId>Mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- JSON 工具类 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> </dependencies> <build> <plugins> <!-- 制作一个可运行的 jar 包需要的插件 --> <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: xiaohhmybatis: # Mapper 的目录 mapper-locations: classpath:mapper*Mapper.xml
然后我们定义一个配置类 DataSourseConfig
用于配置多数据源,首先是申明数据源,按照 application.yml
当中的配置定义两个数据源,注意当中的DataSource 是 javax.sql.DataSource
:
@Primary // 需要一个默认配置的数据源@Bean("user")@ConfigurationProperties(prefix = "spring.datasource.user") // 在yml中配置数据源的前缀public DataSource user() { return DataSourceBuilder.create().build();}@Bean("order")@ConfigurationProperties(prefix = "spring.datasource.order") // 在yml中配置数据源的前缀public DataSource order() { return DataSourceBuilder.create().build();}
然后创建 SqlSessionFactory
:
@Primary // 配置一个这个类型默认的 bean@Bean("userSqlSessionFactory")public SqlSessionFactory userSqlSessionFactory(@Qualifier("user") DataSource user) throws Exception { // 创建bean SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); // 设置数据源 factory.setDataSource(user); // 设置 mapper 文件的扫描 factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/user@Bean("orderSqlSessionFactory")public SqlSessionFactory orderSqlSessionFactory(@Qualifier("order") DataSource order) throws Exception { // 创建bean SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); // 设置数据源 factory.setDataSource(order); // 设置 mapper 文件的扫描 factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/order@Primary // 设置这个类型默认的 bean@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({ // basePackages 是mapper的包路径,sqlSessionTemplateRef 是指定我们创建的 SqlSessionTemplate @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({ // basePackages 是mapper的包路径,sqlSessionTemplateRef 是指定我们创建的 SqlSessionTemplate @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") // 在yml中配置数据源的前缀 public DataSource user() { return DataSourceBuilder.create().build(); } @Bean("order") @ConfigurationProperties(prefix = "spring.datasource.order") // 在yml中配置数据源的前缀 public DataSource order() { return DataSourceBuilder.create().build(); } @Primary // 配置一个这个类型默认的 bean @Bean("userSqlSessionFactory") public SqlSessionFactory userSqlSessionFactory(@Qualifier("user") DataSource user) throws Exception { // 创建bean SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); // 设置数据源 factory.setDataSource(user); // 设置 mapper 文件的扫描 factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/user @Bean("orderSqlSessionFactory") public SqlSessionFactory orderSqlSessionFactory(@Qualifier("order") DataSource order) throws Exception { // 创建bean SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); // 设置数据源 factory.setDataSource(order); // 设置 mapper 文件的扫描 factory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/order @Primary // 设置这个类型默认的 bean @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;@Mapperpublic 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;@Mapperpublic interface UserMapper { int insertUser(User user); List<User> selectUser(User user);}
之后我会将代码提交到 gitee,所以 Mapper.xml、Controller、Service 代码在此处省略,然后我们新增几条用户数据:
查询一下:
同时订单数据库:
查询:
然后在数据库当中查看是否是发送到不同的数据库:
可以确定,确实是存入了两个数据库。
以上是“SpringBoot如何搭建多数据源”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网精选频道!
--结束END--
本文标题: SpringBoot如何搭建多数据源
本文链接: https://lsjlt.com/news/301353.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0