简体   繁体   中英

Cannot connect non primary database in spring boot

I am new to spring boot. Through tutorials, I have build an application. But when I try to connect 2 mysql database, I am successfull in connecting first DB, but for second the code always refer to the primary database and throws error that the table doesn't exist.

There are multiple ways to achieve that depend on requirements also.

  • Create Two Datasource bean while both database url, username, pwd defined in property file. Read them through @Value and create @bean of both source

     @Value("${datasource.url}") private String url; @Value("${datasource.username}") private String username; @Value("${datasource.password}") private String password; @Bean @Primary public DataSource dataSource1() { return DataSourceBuilder.create().username(username).password(password).url(url).build(); } @Bean public DataSource dataSource2() { return DataSourceBuilder.create().username(username).password(password).url(url).build(); }
  • In case you have requirement to sync both database operations, I would suggest to use JTA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM