27 Mart 2023 Pazartesi

SpringData Jdbc JdbcTemplate Multiple Databases Kullanımı

Örnek
application.properties şöyle olsun
spring.datasource.primary.url=jdbc:mysql://localhost:3306/db1
spring.datasource.primary.username=root
spring.datasource.primary.password=password

spring.datasource.secondary.url=jdbc:mysql://localhost:3306/db2
spring.datasource.secondary.username=root
spring.datasource.secondary.password=password
İki DataSource tanımlarız
@Configuration
public class DataSourceConfig {
    
  @Bean
  @Primary
  @ConfigurationProperties(prefix="spring.datasource.primary")
  public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
  }
    
  @Bean
  @ConfigurationProperties(prefix="spring.datasource.secondary")
  public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();
  }
}
İki JdbcTemplateConfig tanımlarız
@Configuration
public class JdbcTemplateConfig {
    
  @Bean
  public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") 
    DataSource primaryDataSource) {
    return new JdbcTemplate(primaryDataSource);
  }
    
  @Bean
  public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") 
    DataSource secondaryDataSource) {
    return new JdbcTemplate(secondaryDataSource);
  }
}
Kullanmak için şöyle yaparız
@Autowired
@Qualifier("primaryJdbcTemplate")
private JdbcTemplate primaryJdbcTemplate;

@Autowired
@Qualifier("secondaryJdbcTemplate")
private JdbcTemplate secondaryJdbcTemplate;

public List<User> getAllUsers() {
    String sql = "SELECT * FROM users";
    return primaryJdbcTemplate.query(sql, new UserMapper());
}

public List<Order> getAllOrders() {
    String sql = "SELECT * FROM orders";
    return secondaryJdbcTemplate.query(sql, new OrderMapper());
}

Hiç yorum yok:

Yorum Gönder