Spring boot 启用第二数据源

发布于:2025-08-30 ⋅ 阅读:(18) ⋅ 点赞:(0)

1. 数据源配置代码:

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "sms.secondary", name = "enabled", havingValue = "true", matchIfMissing = false) //配置是否启用
public class DsDbConfiguration {

    @Bean
    @ConfigurationProperties("spring.datasource.secondary.ds")
    public DruidDataSource jjxxDataSource() {
        DruidDataSource dataSource = (DruidDataSource) DataSourceBuilder.create().type(DruidDataSource.class).build();
        return dataSource;
    }

    @Bean
    public JdbcTemplate jjxxDataTemplate() {
        return new JdbcTemplate(jjxxDataSource());
    }

    @PostConstruct
    public void testConnection() {
        try (Connection conn = jjxxDataSource().getConnection()) {
            DatabaseMetaData meta = conn.getMetaData();
            log.info("MySQL 第二数据源 连接成功! 服务版本: {}", meta.getDatabaseProductVersion());
        } catch (SQLException e) {
            log.error("MySQL  第二数据源 连接失败", e);
            log.error(e.getMessage(), e);
        }
    }
}

2.新建entity

import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Date;

/**
 *  Entity
 * @author 
 * @time   
 */
@Data
@Entity
public class ThirdEntity{

private static final long serialVersionUID = 1L;

	/**
     * 发案时间
     */
    @Column(name = "fasj")
    private Date fasj;

	/**
     * 发案行政区划
     */
    @Column(name = "faxzqh")
    private String faxzqh;

	/**
     *报警电话
     */
    @Column(name = "bjdh")
    private String bjdh;
	
	//省略其他字段
    
}

3. 查询数据:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class JieJingDao {
    private final NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Autowired
    public JieJingDao(@Qualifier("jjxxDataTemplate") JdbcTemplate jdbcTemplate) {
        this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
    }



    // 查询多个记录
    public List<ThirdEntity> queryEntityList(String start, String end) {
        String sql = "SELECT * FROM third_table WHERE  DATE_FORMAT(bjsj,'%Y-%m-%d %H:%i:%S') >=:start and DATE_FORMAT(bjsj,'%Y-%m-%d %H:%i:%S') <= :end";
        MapSqlParameterSource params = new MapSqlParameterSource();
        params.addValue("start", start);
        params.addValue("end", end);
        return namedParameterJdbcTemplate.query(sql, params, new BeanPropertyRowMapper<>(ThirdEntity.class));
    }
   
}

4. 数据源配置信息:

spring.datasource.secondary.ds.url: jdbc:mysql://localhost:3306/thirdDatabase?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=false&rewriteBatchedStatements=true
spring.datasource.secondary.ds.url.username: root
spring.datasource.secondary.ds.url.password: root