多数据源项目配置
Posted 第三眼的思绪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多数据源项目配置相关的知识,希望对你有一定的参考价值。
多数据源复制配置类即可。
package com.yiciyu.transfer.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
@MapperScan(value = LsDbConfig.MAPPER_PACKAGE + ".dao", sqlSessionFactoryRef = "lsSqlSessionFactory")
@Configuration
public class LsDbConfig {
static final String MAPPER_PACKAGE = "com.yiciyu.transfer.ls";
@Bean
public DataSource lsDataSource() {
HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setDriverClassName("com.mysql.jdbc.Driver");
hikariDataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:18033/ls?zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=true&useAffectedRows=true&serverTimezone=Asia/Shanghai");
hikariDataSource.setUsername("username");
hikariDataSource.setPassword("password");
return hikariDataSource;
}
/**
* 参考:com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration
*/
@Bean
public SqlSessionFactory lsSqlSessionFactory(DataSource lsDataSource) throws Exception {
DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
factory.setDataSource(lsDataSource);
factory.setConfigLocation(resourceLoader.getResource("classpath:mybatis-config.xml"));
factory.setMapperLocations(resolver.getResources("classpath:mapper/ls/*.xml"));
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
paginationInterceptor.setDbType(DbType.MYSQL);
factory.setPlugins(paginationInterceptor);
return factory.getObject();
}
@Bean
public DataSourceTransactionManager lsTransactionManager(DataSource lsDataSource) {
return new DataSourceTransactionManager(lsDataSource);
}
}
以上是关于多数据源项目配置的主要内容,如果未能解决你的问题,请参考以下文章
Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段
spring框架中多数据源创建加载并且实现动态切换的配置实例代码