参考链接
https://blog.csdn.net/tuesdayma/article/details/81081666
实现思路配置多个数据源,然后通过扫描不同的包路径来实现不同的包下的mapper使用不同的数据源
package com.ganlong.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.zaxxer.hikari.HikariDataSource;
@Configuration
@MapperScan(value= {"com.ganlong.mapper.test1"},sqlSessionFactoryRef="springbootDemoSqlSessionFactory")
public class SpringbootDemoConfig {
@Bean
@Primary
public DataSource springbootDemoDataSource() {
DataSourceProperties dataSourceProperties=new DataSourceProperties();
dataSourceProperties.setUsername("root");
dataSourceProperties.setPassword("123456");
dataSourceProperties.setUrl("jdbc:mysql://192.168.1.131/springbootDemo?characterEncoding=utf-8&useSSL=false");
return dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
@Bean
@Primary
public SqlSessionFactory springbootDemoSqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(springbootDemoDataSource());
return sqlSessionFactoryBean.getObject();
}
}
package com.ganlong.config;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.zaxxer.hikari.HikariDataSource;
@Configuration
@MapperScan(value= {"com.ganlong.mapper.test2"},sqlSessionFactoryRef="springDataJpaSqlSessionFactory")
public class SpringDataJpaConfig {
@Bean
public DataSource springDataJpaDataSource() {
DataSourceProperties dataSourceProperties=new DataSourceProperties();
dataSourceProperties.setUsername("root");
dataSourceProperties.setPassword("123456");
dataSourceProperties.setUrl("jdbc:mysql://192.168.1.131/spring_data_jpa?characterEncoding=utf-8&useSSL=false");
return dataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();
}
@Bean
public SqlSessionFactory springDataJpaSqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(springDataJpaDataSource());
return sqlSessionFactoryBean.getObject();
}
}
网友评论