【Springboot】多数据源配置使用jdbcTemplate执行SQL

31 篇文章 0 订阅

数据源配置文件

# 多数据源配置
spring:
  datasource:
    ds1:
      driverClassName: org.postgresql.Driver
      jdbc-url: jdbc:postgresql://xxx:5432/xxxx?currentSchema=public
      username: admin
      password: admin
    ds2:
      driverClassName: org.postgresql.Driver
      jdbc-url: jdbc:postgresql://xxx:5432/xxx?currentSchema=public
      username: admin
      password: admin
  jpa:
    hibernate:
      dialect: org.hibernate.dialect.PostgreSQLDialect
    open-in-view: true
    show-sql: true
    database-platform: org.hibernate.dialect.PostgreSQLDialect

配置类

/**
 * 多数据源配置
 */
@Configuration
public class DataSourceConfig {

    @Bean(name = "dataSource1")
    @Qualifier("dataSource1")
    @Primary
    @ConfigurationProperties(prefix="spring.datasource.ds1")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dataSource2")
    @Qualifier("dataSource2")
    @ConfigurationProperties(prefix="spring.datasource.ds2")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

}
@Configuration
public class JdbcTemplateConfig {

	@Bean(name = "jdbcTemplate1")
    @Qualifier("jdbcTemplate1")
    JdbcTemplate jdbcTemplateTwo(@Qualifier("dataSource1") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "jdbcTemplate2")
    @Qualifier("jdbcTemplate2")
    JdbcTemplate jdbcTemplateTwo(@Qualifier("dataSource2") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

之后在其他地方就可以使用到对应数据源的jdbcTemplate了

@Autowired
@Qualifier("jdbcTemplate2")
private JdbcTemplate jdbcTemplate;

JdbcTemplate使用方法

  1. 仅执行SQL
jdbcTemplate.execute(sql);
  1. 查询一条记录,注意:queryForObject 没有查询到内容会有异常,不会返回null
Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
  1. 解决上面抛出异常问题,使用query
		List<byte[]> list = jdbcTemplate.query(sql,new BytesRowMapper());
        if(list.size() == 0){
            return null;
        }else {
            return list.get(0);
        }
public class BytesRowMapper implements RowMapper<byte[]> {
    @Override
    public byte[] mapRow(ResultSet resultSet, int i) throws SQLException {
        return resultSet.getBytes(1);
    }
}

自定义rowMapper为所欲为,随便映射查询结果到自己定义的类

public class StateRowMapper implements RowMapper<PGState> {
    @Override
    public State mapRow(ResultSet resultSet, int i) throws SQLException {
        return new State(resultSet.getString(1),resultSet.getString(2),resultSet.getTimestamp(3));
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值