首页>>后端>>SpringBoot->SpringBoot+Mybatis配置多源数据库

SpringBoot+Mybatis配置多源数据库

时间:2023-11-30 本站 点击:1

方法一

配置多个数据库

spring:datasource:master:driver-class-name:com.mysql.jdbc.Driverjdbc-url:jdbc:mysql://localhost:3305/se?useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8username:rootpassword:rootmovies:driver-class-name:com.mysql.jdbc.Driverjdbc-url:jdbc:mysql://localhost:3307/se_movies?useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8username:rootpassword:root

配置数据库连接

packagecom.my.equipment.config.oldConfig;

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.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.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration @MapperScan(basePackages = "com.my.equipment.web.seMoviesDao", sqlSessionTemplateRef = "seMoviesSqlSessionTemplate") public class SeMoviesDatasourceConfig {

@Bean(name="seMoviesDataSource")@ConfigurationProperties(prefix="spring.datasource.movies")publicDataSourcetestDataSource(){returnDataSourceBuilder.create().build();}@Bean(name="seMoviesSqlSessionFactory")publicSqlSessionFactorytestSqlSessionFactory(@Qualifier("seMoviesDataSource")DataSourcedataSource)throwsException{SqlSessionFactoryBeanbean=newSqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(newPathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));returnbean.getObject();}@Bean(name="seMoviesTransactionManager")publicDataSourceTransactionManagertestTransactionManager(@Qualifier("seMoviesDataSource")DataSourcedataSource){returnnewDataSourceTransactionManager(dataSource);}@Bean(name="seMoviesSqlSessionTemplate")publicSqlSessionTemplatetestSqlSessionTemplate(@Qualifier("seMoviesSqlSessionFactory")SqlSessionFactorysqlSessionFactory)throwsException{returnnewSqlSessionTemplate(sqlSessionFactory);}

}

```javapackagecom.my.equipment.config.oldConfig;importorg.apache.ibatis.session.SqlSessionFactory;importorg.mybatis.spring.SqlSessionFactoryBean;importorg.mybatis.spring.SqlSessionTemplate;importorg.mybatis.spring.annotation.MapperScan;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.boot.jdbc.DataSourceBuilder;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Primary;importorg.springframework.core.io.support.PathMatchingResourcePatternResolver;importorg.springframework.jdbc.datasource.DataSourceTransactionManager;importjavax.sql.DataSource;@Configuration@MapperScan(basePackages="com.my.equipment.web.dao",sqlSessionTemplateRef="seSqlSessionTemplate")publicclassSeDatasourceConfig{@Bean(name="seDataSource")@ConfigurationProperties(prefix="spring.datasource.master")@PrimarypublicDataSourcetestDataSource(){returnDataSourceBuilder.create().build();}@Bean(name="seSqlSessionFactory")@PrimarypublicSqlSessionFactorytestSqlSessionFactory(@Qualifier("seDataSource")DataSourcedataSource)throwsException{SqlSessionFactoryBeanbean=newSqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(newPathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));returnbean.getObject();}@Bean(name="seTransactionManager")@PrimarypublicDataSourceTransactionManagertestTransactionManager(@Qualifier("seDataSource")DataSourcedataSource){returnnewDataSourceTransactionManager(dataSource);}@Bean(name="seSqlSessionTemplate")@PrimarypublicSqlSessionTemplatetestSqlSessionTemplate(@Qualifier("seSqlSessionFactory")SqlSessionFactorysqlSessionFactory)throwsException{returnnewSqlSessionTemplate(sqlSessionFactory);}}

方法2

1.配置多个数据库

spring:datasource:master:driver-class-name:com.mysql.jdbc.Driverjdbc-url:jdbc:mysql://localhost:3305/se?useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8username:rootpassword:rootslave:driver-class-name:com.mysql.jdbc.Driverjdbc-url:jdbc:mysql://localhost:3310/se?useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8username:rootpassword:rootmovies:driver-class-name:com.mysql.jdbc.Driverjdbc-url:jdbc:mysql://localhost:3307/se_movies?useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8username:rootpassword:root

2.配置数据库连接

定义多元数据库

packagecom.my.equipment.utils;publicenumDBTypeEnum{MASTER,SLAVE,MOVIES;}

定义数据源切换

packagecom.my.equipment.utils;publicclassDBContextHolder{privatestaticfinalThreadLocal<DBTypeEnum>contextHolder=newThreadLocal<>();publicstaticvoidset(DBTypeEnumdbTypeEnum){contextHolder.set(dbTypeEnum);}publicstaticDBTypeEnumget(){returncontextHolder.get();}publicstaticvoidmaster(){set(DBTypeEnum.MASTER);System.out.println("写");}publicstaticvoidslave(){set(DBTypeEnum.SLAVE);System.out.println("读");}publicstaticvoidmovies(){set(DBTypeEnum.MOVIES);System.out.println("movies");}publicstaticvoidclear(){contextHolder.remove();}}

重写路由选择类

packagecom.my.equipment.utils;importorg.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;importorg.springframework.lang.Nullable;publicclassMyRoutingDataSourceextendsAbstractRoutingDataSource{@Nullable@OverrideprotectedObjectdetermineCurrentLookupKey(){returnDBContextHolder.get();}}

配置Mybatis SqlSessionFactory 和事务管理器

packagecom.my.equipment.config;importorg.apache.ibatis.jdbc.SQL;importorg.apache.ibatis.session.SqlSessionFactory;importorg.mybatis.spring.SqlSessionFactoryBean;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.core.io.support.PathMatchingResourcePatternResolver;importorg.springframework.core.io.support.ResourcePatternResolver;importorg.springframework.jdbc.datasource.DataSourceTransactionManager;importorg.springframework.transaction.PlatformTransactionManager;importorg.springframework.transaction.annotation.EnableTransactionManagement;importjavax.annotation.Resource;importjavax.sql.DataSource;@Configuration@EnableTransactionManagementpublicclassMyBatisConfig{@Value("${mybatis.mapper-locations}")privateStringmapperLocation;@Resource(name="myRoutingDataSource")privateDataSourcemyRoutingDataSource;@BeanpublicSqlSessionFactorysqlSessionFactory()throwsException{SqlSessionFactoryBeansqlSessionFactoryBean=newSqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(myRoutingDataSource);ResourcePatternResolverresolver=newPathMatchingResourcePatternResolver();sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocation));returnsqlSessionFactoryBean.getObject();}@BeanpublicPlatformTransactionManagerplatformTransactionManager(){returnnewDataSourceTransactionManager(myRoutingDataSource);}}

配置数据源

packagecom.my.equipment.config;importcom.my.equipment.utils.DBTypeEnum;importcom.my.equipment.utils.MyRoutingDataSource;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.boot.jdbc.DataSourceBuilder;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importjavax.sql.DataSource;importjava.util.HashMap;importjava.util.Map;@ConfigurationpublicclassDatasourceConfig{/***配置从数据库*@return*/@Bean(name="slaveDataSource")@ConfigurationProperties("spring.datasource.slave")publicDataSourceslaveDataSource(){returnDataSourceBuilder.create().build();}/***配置主数据库*@return*/@Bean(name="masterDataSource")@ConfigurationProperties("spring.datasource.master")publicDataSourcemasterDataSource(){returnDataSourceBuilder.create().build();}@Bean(name="moviesDataSource")@ConfigurationProperties("spring.datasource.movies")publicDataSourcemoviesDataSource(){returnDataSourceBuilder.create().build();}@BeanpublicDataSourcemyRoutingDataSource(@Qualifier("slaveDataSource")DataSourceslaveDataSource,@Qualifier("masterDataSource")DataSourcemasterDataSource,@Qualifier("moviesDataSource")DataSourcemoviesDataSource){Map<Object,Object>targetDataSource=newHashMap<>();targetDataSource.put(DBTypeEnum.MASTER,masterDataSource);targetDataSource.put(DBTypeEnum.SLAVE,slaveDataSource);targetDataSource.put(DBTypeEnum.MOVIES,moviesDataSource);MyRoutingDataSourcemyRoutingDataSource=newMyRoutingDataSource();//找不到用默认数据源myRoutingDataSource.setDefaultTargetDataSource(masterDataSource);//可选择的目标数据源myRoutingDataSource.setTargetDataSources(targetDataSource);returnmyRoutingDataSource;}}

切面实现数据源切换

packagecom.my.equipment.config.oldConfig;0


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:/SpringBoot/2608.html