Springboot项目同时连接SQLServer数据库和MySql数据库

本文记录了在Springboot项目中如何配置并同时连接SQLServer和MySQL数据库的过程,通过yaml文件设置数据源,并提供了数据库工具类的代码示例,实现了对不同数据库的jdbc操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天的任务就是把同时连接SQLServer和MySql的环境搭配好

在组长的帮助下,一步一步测试摸索后终于完成了!

首先是把俩个数据源写在同一个yaml里面

 

配置完成后再去创建工具类

MySql工具类代码:

package com.gl.framework.config;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.jdbc.core.JdbcTemplate;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
public class MySqlConfig {
    private final Logger LOG = LoggerFactory.getLogger(getClass());

    @Value("${spring.datasource.druid.url}")
    private String jdbcUrl;
    @Value("${spring.datasource.driverClassName}")
    private String jdbcDriver;
    @Value("${spring.datasource.druid.username}")
    private String jdbcUserName;
    @Value("${spring.datasource.druid.password}")
    private String jdbcPassword;

    @Value("${spring.datasource.druid.initialSize}")
    private Integer initi
可以在Spring Boot项目同时连接MySQLSQL Server数据库,具体步骤如下: 1. 在pom.xml文件中添加MySQLSQL Server数据库的驱动依赖,例如: ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>com.microsoft.sqlserver</groupId> <artifactId>mssql-jdbc</artifactId> <version>${sqlserver.version}</version> </dependency> ``` 2. 在application.yml文件中配置两个数据源,例如: ```yaml spring: datasource: primary: url: jdbc:mysql://localhost:3306/db_mysql driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 secondary: url: jdbc:sqlserver://localhost:1433;databaseName=db_sqlserver driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver username: sa password: 123456 ``` 3. 在Spring Boot项目中配置两个数据源,例如: ```java @Configuration public class DataSourceConfig { @Bean(name = "primaryDataSource") @Qualifier("primaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "secondaryDataSource") @Qualifier("secondaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } } ``` 4. 在MyBatis中配置两个数据源,并指定使用哪个数据源,例如: ```java @Configuration @MapperScan(basePackages = "com.example.mapper", sqlSessionTemplateRef = "primarySqlSessionTemplate") public class MybatisConfig { @Bean(name = "primarySqlSessionFactory") @Primary public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "secondarySqlSessionFactory") public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("secondaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); return bean.getObject(); } @Bean(name = "primarySqlSessionTemplate") @Primary public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } @Bean(name = "secondarySqlSessionTemplate") public SqlSessionTemplate secondarySqlSessionTemplate(@Qualifier("secondarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } @Bean @Primary public PlatformTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean public PlatformTransactionManager secondaryTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } } ``` 在定义Mapper时,可以通过@Qualifier注解指定使用哪个数据源的SqlSessionTemplate,例如: ```java public interface UserMapper { @Select("SELECT * FROM user") @Results({ @Result(property = "id", column = "id"), @Result(property = "name", column = "name"), @Result(property = "age", column = "age") }) List<User> getAllUsers(); @Select("SELECT * FROM user WHERE id = #{id}") @Results({ @Result(property = "id", column = "id"), @Result(property = "name", column = "name"), @Result(property = "age", column = "age") }) User getUserById(@Param("id") Long id); } ``` 在Service层中,可以通过@Autowired注解注入UserMapper,并指定使用哪个数据源的SqlSessionTemplate,例如: ```java @Service public class UserService { @Autowired @Qualifier("primarySqlSessionTemplate") private SqlSessionTemplate primarySqlSessionTemplate; @Autowired @Qualifier("secondarySqlSessionTemplate") private SqlSessionTemplate secondarySqlSessionTemplate; public List<User> getAllUsersFromPrimaryDataSource() { UserMapper userMapper = primarySqlSessionTemplate.getMapper(UserMapper.class); return userMapper.getAllUsers(); } public User getUserByIdFromSecondaryDataSource(Long id) { UserMapper userMapper = secondarySqlSessionTemplate.getMapper(UserMapper.class); return userMapper.getUserById(id); } } ``` 这样就可以在Spring Boot项目同时连接MySQLSQL Server数据库了。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值