SpringBoot配置Mysql+达梦双数据源
在Spring Boot项目中配置MySQL和达梦(DMDB)双数据源,你需要定义两个数据源的配置,并且为每个数据源创建DataSource
实例。以下是一个简化的示例配置:
- 在
application.properties
或application.yml
中添加两个数据源的配置信息:
# MySQL 数据源配置
spring.datasource.mysql.url=jdbc:mysql://localhost:3306/your_mysql_db?useSSL=false&serverTimezone=UTC
spring.datasource.mysql.username=your_mysql_username
spring.datasource.mysql.password=your_mysql_password
spring.datasource.mysql.driver-class-name=com.mysql.cj.jdbc.Driver
# 达梦数据源配置
spring.datasource.dameng.url=jdbc:dm://localhost:5236/your_dameng_db
spring.datasource.dameng.username=your_dameng_username
spring.datasource.dameng.password=your_dameng_password
spring.datasource.dameng.driver-class-name=dm.jdbc.driver.DmDriver
- 创建配置类,配置两个数据源:
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 DataSourceConfig {
@Primary
@Bean(name = "mysqlDataSource")
@ConfigurationProperties(prefix = "spring.datasource.mysql")
public DataSource mysqlDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "damengDataSource")
@ConfigurationProperties(prefix = "spring.datasource.dameng")
public DataSource damengDataSource() {
return DataSourceBuilder.create().build();
}
}
- 配置
JdbcTemplate
和SqlSessionFactory
,分别为每个数据源创建:
import org.mybatis.spring.SqlSessionFactoryBean;
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.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "your.package.name", sqlSessionFactoryRef = "sqlSessionFactoryMysql")
public class MyBatisConfig {
@Bean(name = "jdbcTemplateMysql")
public JdbcTemplate jdbcTemplateM
评论已关闭