1.用idea初始化一个springboot项目
包结构如下:
2.具体配置如下:
1.application.yml:
#DataSource
spring:
datasource:
test1:
jdbcUrl: jdbc:mysql://localhost:3306/springbootstudy
username: root
password: 1123
driverClassName : com.mysql.jdbc.Driver
test2:
jdbcUrl: jdbc:mysql://localhost:3306/springbootstudy1
username: root
password: 1123
driverClassName : com.mysql.jdbc.Driver
2.DtatasourceConfig:(配置两个数据源方法相同,其中用@Primary指定一个为主数据源,不然启动会报错)
@Configuration
@MapperScan(basePackages = "com.sjy.springbootdemo.domain.repository",sqlSessionFactoryRef = "test1SqlSessionFactory")
public class Datasource1Config {
@Bean(name = "test1DataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource.test1")
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
}
@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/**/*.xml"));
return bean.getObject();
}
}
3.测试成功
service层同时调用两个数据层:
public Integer addItem(Person person) {
Integer i1 = personRepository1.addPerson(person);
Integer i2 = personRepository.addPerson(person);
return i1+i2;
}
web层:
@RestController
public class MvcController {
@Autowired
private MvcService mvcService;
@GetMapping(value = "add/item1")
public String test1(Person person){
Integer i = mvcService.addItem(person);
if (i>1){
return "success";
}else {
return "failure";
}
}
}
前台访问结果:
后台数据库:
4.总结
此种方式通过不同数据源用@MapperScan扫描不同的mapper包实现(分包)