Spring Boot 集成 JdbcTemplate 实现多数据源配置

在实际开发中,我们会遇到一个应用需要访问多个数据源的情况。因此,我们需要配置多个数据源。使用 JdbcTemplate 实现多数据源配置是比较简单的。

添加相关依赖

1
<dependency>
2
  <groupId>org.springframework.boot</groupId>
3
  <artifactId>spring-boot-starter-jdbc</artifactId>
4
</dependency>
5
<dependency>
6
  <groupId>mysql</groupId>
7
  <artifactId>mysql-connector-java</artifactId>
8
  <version>5.1.35</version>
9
</dependency>
10
<dependency>
11
  <groupId>com.alibaba</groupId>
12
  <artifactId>druid</artifactId>
13
  <version>1.0.14</version>
14
</dependency>

配置数据源信息

  • application.properties
1
# 数据源一
2
spring.datasource.druid.one.driver-class-name=com.mysql.jdbc.Driver
3
spring.datasource.druid.one.url=jdbc:mysql://localhost:3306/game?useUnicode=true&characterEncoding=utf-8
4
spring.datasource.druid.one.username=root
5
spring.datasource.druid.one.password=root
6
7
# 数据源二
8
spring.datasource.druid.two.driver-class-name=com.mysql.jdbc.Driver
9
spring.datasource.druid.two.url=jdbc:mysql://localhost:3306/product?useUnicode=true&characterEncoding=utf-8
10
spring.datasource.druid.two.username=root
11
spring.datasource.druid.two.password=root

创建 DataSource 和 JdbcTemplate

数据源一

这里将数据源一作为主数据源,并添加 @Primary 注解。

1
@Configuration
2
public class DataSourceOneConfig {
3
4
    @Bean(name = "DataSourceOne")
5
    @Primary
6
    @ConfigurationProperties(prefix = "spring.datasource.druid.one")
7
    public DataSource dataSource() {
8
        return new DruidDataSource();
9
    }
10
11
    @Bean(name = "JdbcTemplateOne")
12
    @Primary
13
    public JdbcTemplate jdbcTemplate(@Qualifier("DataSourceOne") DataSource dataSource) {
14
        return new JdbcTemplate(dataSource);
15
    }
16
}

数据源二

1
@Configuration
2
public class DataSourceTwoConfig {
3
4
    @Bean(name = "DataSourceTwo")
5
    @ConfigurationProperties(prefix = "spring.datasource.druid.two")
6
    public DataSource dataSource() {
7
        return new DruidDataSource();
8
    }
9
10
    @Bean(name = "JdbcTemplateTwo")
11
    public JdbcTemplate jdbcTemplate(@Qualifier("DataSourceTwo") DataSource dataSource) {
12
        return new JdbcTemplate(dataSource);
13
    }
14
}

编写 DAO 和 Service

上面的配置工作完成后,接下来编写数据库操作的 DAO 类和 Service 类。

数据源一

  • 编写 DAO 类
1
@Repository
2
public class UserRepository {
3
4
    @Autowired
5
    @Qualifier("JdbcTemplateOne") // 由于是多数据源,在注入 JdbcTemplate 时,需指明是哪个数据源的。
6
    private JdbcTemplate jdbcTemplate;
7
8
    public int insertUser(User user) {
9
        String sql = "INSERT INTO user(username, password) VALUES(?,?)";
10
        int count = jdbcTemplate.update(sql, user.getUsername(), user.getPassword());
11
        return count;
12
13
    }
14
}
  • 编写 Service 类
1
@Service
2
public class UserService {
3
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);
4
5
    @Autowired
6
    private UserRepository userRepository;
7
8
    public void insertUser(User user){
9
        userRepository.insertUser(user);
10
        logger.info("Insert user success");
11
    }
12
}

数据源二

  • 编写 DAO 类
1
@Repository
2
public class ProductRepository {
3
4
    @Autowired
5
    @Qualifier("JdbcTemplateTwo")
6
    private JdbcTemplate jdbcTemplate;
7
8
    public Integer insertProduct(Product product) {
9
        String sql = "INSERT INTO product(product_name, price, address) VALUES(?,?,?)";
10
        int count = jdbcTemplate.update(sql, product.getProductName(), product.getPrice(), product.getAddress());
11
        return count;
12
13
    }
14
15
}
  • 编写 Service 类
1
@Service
2
public class ProductService {
3
4
    private static final Logger logger = LoggerFactory.getLogger(ProductService.class);
5
6
    @Autowired
7
    private ProductRepository productRepository;
8
9
    public void insertProduct(Product product) {
10
        productRepository.insertProduct(product);
11
        logger.info("Insert product success");
12
    }
13
}

最后,详细代码可以查看本示例的 Demo。

源码地址

springboot-multidatasource-jdbctemplate