首页 > 基础资料 博客日记
Springboot 项目配置多数据源
2025-08-20 18:00:02基础资料围观45次
文章Springboot 项目配置多数据源分享给大家,欢迎收藏Java资料网,专注分享技术知识
基础环境
java8、springboot2.2.13、mybatis、mysql5.x、oracle
项目配置
1.application.yml
spring:
datasource:
mysql1:
username: abc
password: 123456
url: jdbc:mysql://127.0.0.1:3306/panda?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=GMT%2B8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
oracle1:
url: jdbc:oracle:thin:@127.0.0.1:1521:oracle
username: default
password: 123456
driver-class-name: oracle.jdbc.driver.OracleDriver
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
2.数据源配置
有三个注意点,其一是 @Primary 作用是标记哪个是主数据源(默认不指定数据源时会调用的数据源);其二是 basePackages 配置的是实际mapper路径,不同数据源路径不能混淆;其三是 setMapperLocations 配置的路径要加上 “classpath:” 前缀,才能找到对应包下的 .xml 文件。
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 javax.sql.DataSource;
@Configuration
public class AllDataSourceConfig {
@Bean(name = "safeDrivingDataSource")
@ConfigurationProperties(prefix = "spring.datasource.mysql1") // application.yml 中对应属性的前缀
@Primary
public DataSource safeDrivingDataSource() {
return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
}
@Bean(name = "emmpAppDataSource")
@ConfigurationProperties(prefix = "spring.datasource.oracle1")
public DataSource emmpappDataSource() {
return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
}
}
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.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;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.emmp.safedriving.dao.mapper.ds1", sqlSessionFactoryRef = "safeDrivingSqlSessionFactory")
public class SafeDrivingDataSourceConfig {
@Bean("safeDrivingSqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory(@Qualifier("safeDrivingDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
org.apache.ibatis.session.Configuration mybatisConfig = new org.apache.ibatis.session.Configuration();
mybatisConfig.setLazyLoadingEnabled(true);
mybatisConfig.setAggressiveLazyLoading(false);
mybatisConfig.setMapUnderscoreToCamelCase(true);
sqlSessionFactoryBean.setConfiguration(mybatisConfig);
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath:com/emmp/safedriving/dao/mapper/ds1/xml/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean("safeDrivingDataSourceTransactionManager")
@Primary
public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("safeDrivingDataSource") DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "safeDrivingSqlSessionTemplate")
@Primary
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("safeDrivingSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
}
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.emmp.safedriving.dao.mapper.ds2", sqlSessionFactoryRef = "emmpAppSqlSessionFactory")
public class EmmpAppDataSourceConfig {
@Bean("emmpAppSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("emmpAppDataSource") DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
org.apache.ibatis.session.Configuration mybatisConfig = new org.apache.ibatis.session.Configuration();
mybatisConfig.setLazyLoadingEnabled(true);
mybatisConfig.setAggressiveLazyLoading(false);
mybatisConfig.setMapUnderscoreToCamelCase(true);
sqlSessionFactoryBean.setConfiguration(mybatisConfig);
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath:com/emmp/safedriving/dao/mapper/ds2/xml/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean("emmpAppDataSourceTransactionManager")
public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("emmpAppDataSource") DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
@Bean(name = "emmpAppSqlSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(@Qualifier("emmpAppSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
}
3.启动类配置
不需要再添加 @MapperScan
@SpringBootApplication(
exclude = {
DataSourceAutoConfiguration.class, // 排除默认数据源配置
DataSourceTransactionManagerAutoConfiguration.class, // 排除默认事务管理器
MybatisAutoConfiguration.class // 排除 MyBatis 默认配置
}
)
4.mapper 定义示例
// 映射对象定义
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Data
@Builder
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class DriverInfo {
private Long id;
private String driverName;
}
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface DriverInfoMapper {
List<DriverInfo> queryAll();
List<DriverInfo> queryByCellphone(String cellphone);
}
对应 DriverInfoMapper.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.emmp.safedriving.dao.mapper.ds2.DriverInfoMapper">
<resultMap id="entity" type="com.emmp.safedriving.dao.entity.DriverInfo">
<result property="id" column="ID"/>
<result property="driverName" column="DRIVERNAME"/>
</resultMap>
<select id="queryAll" resultMap="entity">
SELECT * FROM DRIVER_INFO
</select>
<select id="queryByCellphone" resultMap="entity">
SELECT * FROM DRIVER_INFO
WHERE CELLPHONE = #{cellphone}
ORDER BY ID DESC
</select>
</mapper>
文章来源:https://www.cnblogs.com/pandacode/p/19049136
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:
相关文章
最新发布
- springboot~3.x项目中使用集成测试
- Java测试类、工具类与JavaBean对比解析
- SpringBoot-日志
- springboot~http2的支持
- 解疑释惑 - 日志体系之 slf4j + logback 组合(一)
- Web server failed to start. Port 8080 was already in use. 端口被占用
- Springboot 项目配置多数据源
- 伙伴匹配系统(移动端 H5 网站(APP 风格)基于Spring Boot 后端 + Vue3 - 05
- 剑指offer-23、搜索⼆叉树的后序遍历序列
- 一个表示金额的数字是 100000000L,这是多少米?