-
yaml配置数据库
spring: datasource: db1: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://127.0.0.1:3306/javatest?serverTimezone=CST username: root password: root1234 db2: driver-class-name: com.mysql.cj.jdbc.Driver jdbc-url: jdbc:mysql://127.0.0.1:3306/mytest?serverTimezone=CST username: root password: root1234
-
创建配置类配置所有数据库
@Configuration public class DBConfig { @Bean(name="db1") @ConfigurationProperties("spring.datasource.db1")//导入配置 public DataSource datasource1(){ return DataSourceBuilder.create().build(); } @Bean(name="db2") @ConfigurationProperties("spring.datasource.db2")//导入配置 public DataSource datasource2(){ return DataSourceBuilder.create().build(); } }
-
创建类绑定单个库对应dao包
@Configuration //basePackages包名 @MapperScan(basePackages = "com.example.demo3.dao",sqlSessionFactoryRef = "sqlSessionFactory1") public class DB1Config { @Autowired @Qualifier("db1")//对应配置类中的bean的name private DataSource dataSource; @Bean public SqlSessionFactory sqlSessionFactory1() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); return factoryBean.getObject(); } @Bean public SqlSessionTemplate sqlSessionTemplate1() throws Exception { SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1()); return template; } }
注:db2同理,简单来说,一个dao包一个数据库
-
在此dao包下创建dao类
@Repository public interface UserDao { @Select("select username,password from myuser") List<Myuser> selectAll(); }
-
自动注入
@Autowired private UserDao userDao;
SpringBoot集成Mybatis对多数据源的配置
最新推荐文章于 2024-05-30 16:07:57 发布