北京做网站一般多少钱,微信开发者工具怎么下载,免费淘宝关键词工具,二 网站建设的目的及功能定位一、引言
在开发中#xff0c;我们经常会遇到需要连接多个数据库的情况。使用Spring Boot和MyBatis框架可以很方便地实现多数据源的配置和使用。本文将详细介绍如何在Spring Boot项目中使用多数据源。
二、实操
1、添加所需的依赖#xff1a;
!-- Spring Boot Starte…一、引言
在开发中我们经常会遇到需要连接多个数据库的情况。使用Spring Boot和MyBatis框架可以很方便地实现多数据源的配置和使用。本文将详细介绍如何在Spring Boot项目中使用多数据源。
二、实操
1、添加所需的依赖
!-- Spring Boot Starter for MyBatis --
dependencygroupIdorg.mybatis.spring.boot/groupIdartifactIdmybatis-spring-boot-starter/artifactIdversion2.2.0/version
/dependency
!-- 数据库驱动依赖 --
dependencygroupIdcom.h2database/groupIdartifactIdh2/artifactIdscoperuntime/scope
/dependency
!-- 其他数据库驱动依赖 --
...2、配置数据源和MyBatis会话工厂
在 application.properties 或 application.yml 文件中配置主数据源
spring.datasource.urljdbc:mysql://localhost:3306/db1
spring.datasource.usernameroot
spring.datasource.passwordpassword
spring.datasource.driver-class-namecom.mysql.cj.jdbc.Driver建一个类来配置第二个数据源和MyBatis会话工厂例如 SecondaryDataSourceConfig
Configuration
MapperScan(basePackages com.example.secondary, sqlSessionTemplateRef secondarySqlSessionTemplate)
public class SecondaryDataSourceConfig {Bean(name secondaryDataSource)ConfigurationProperties(prefix spring.datasource.secondary)public DataSource secondaryDataSource() {return DataSourceBuilder.create().build();}Bean(name secondarySqlSessionFactory)public SqlSessionFactory secondarySqlSessionFactory(Qualifier(secondaryDataSource) DataSource secondaryDataSource) throws Exception {SqlSessionFactoryBean sessionFactory new SqlSessionFactoryBean();sessionFactory.setDataSource(secondaryDataSource);return sessionFactory.getObject();}Bean(name secondarySqlSessionTemplate)public SqlSessionTemplate secondarySqlSessionTemplate(Qualifier(secondarySqlSessionFactory) SqlSessionFactory sqlSessionFactory) {return new SqlSessionTemplate(sqlSessionFactory);}
}在 application.properties 或 application.yml 文件中配置第二个数据源
spring.datasource.secondary.urljdbc:mysql://localhost:3306/db2
spring.datasource.secondary.usernameroot
spring.datasource.secondary.passwordpassword
spring.datasource.secondary.driver-class-namecom.mysql.cj.jdbc.Driver3、创建两个数据库对应的Mapper接口和Mapper XML文件
主数据源的Mapper接口、Mapper XML文件
package com.example.primary;// import语句Mapper
public interface PrimaryMapper {// 方法定义
}!-- primary-mapper.xml --
?xml version1.0 encodingUTF-8?
!DOCTYPE mapper PUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.example.primary.PrimaryMapper!-- SQL语句定义 --
/mapper第二个数据源的Mapper接口、Mapper XML文件与上面类似只需将包名、namespace和SQL语句替换为对应的内容。
使用多数据源
在需要使用主数据源的地方注入 PrimaryMapper
Autowired
private PrimaryMapper primaryMapper;在需要使用第二个数据源的地方注入 SecondaryMapper
Autowired
private SecondaryMapper secondaryMapper;这样你就可以在Spring Boot项目中使用多个数据源并使用MyBatis进行数据库操作了。需要注意的是上述示例中使用了两个数据源你可以根据自己的需求配置更多的数据源只需按照类似的方式添加配置和代码。