整合多数据源
这里有两种,分包数据源和注解数据源,这里讲分包数据源
配置文件中新增两个数据源
spring.datasource.test1.driverClassName = com.mysql.jdbc.Driver spring.datasource.test1.url = jdbc:mysql://localhost:3306/test01?useUnicode=true&characterEncoding=utf-8 spring.datasource.test1.username = root spring.datasource.test1.password = root
spring.datasource.test2.driverClassName = com.mysql.jdbc.Driver spring.datasource.test2.url = jdbc:mysql://localhost:3306/test02?useUnicode=true&characterEncoding=utf-8 spring.datasource.test2.username = root spring.datasource.test2.password = root |
配置文件中新增两个数据源
@Configuration// 注册到springboot容器中 @MapperScan(basePackages = "com.itmayiedu.user1", sqlSessionFactoryRef = "test1SqlSessionFactory") publicclass DataSource1Config {
/** * * @methodDesc: 功能描述:(配置test1数据库) * @param: @return * @createTime:2017年9月17日下午3:16:44 * @returnType:@return DataSource */ @Bean(name = "test1DataSource") @Primary @ConfigurationProperties(prefix = "spring.datasource.test1") public DataSource testDataSource() { return DataSourceBuilder.create().build(); }
/** * * @methodDesc: 功能描述:(test1 sql会话工厂) * @param: @param * dataSource * @param: @return * @param: @throws * Exception * @createTime:2017年9月17日下午3:17:08 * @returnType:@param dataSource * @returnType:@return * @returnType:@throws Exception SqlSessionFactory */ @Bean(name = "test1SqlSessionFactory") @Primary public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); // bean.setMapperLocations( // new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml")); returnbean.getObject(); }
/** * * @methodDesc: 功能描述:(test1 事物管理) * @param: @param * dataSource * @param: @return * @param: @throws * Exception * @createTime:2017年9月17日下午3:17:08 * @returnType:@param dataSource * @returnType:@return * @returnType:@throws Exception SqlSessionFactory */ @Bean(name = "test1TransactionManager") @Primary public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) { returnnew DataSourceTransactionManager(dataSource); }
@Bean(name = "test1SqlSessionTemplate") public SqlSessionTemplate testSqlSessionTemplate( @Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { returnnew SqlSessionTemplate(sqlSessionFactory); }
} |
创建分包Mapper
public interface User1Mapper { @Insert("insert into users values(null,#{name},#{age});") public int addUser(@Param("name") String name, @Param("age") Integer age); } |
启动项目
@ComponentScan(basePackages = "com.itmayiedu") @EnableAutoConfiguration publicclass App { publicstaticvoid main(String[] args) { SpringApplication.run(App.class, args); } } |