数据源配置文件
# 多数据源配置
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使用方法
- 仅执行SQL
jdbcTemplate.execute(sql);
- 查询一条记录,注意:queryForObject 没有查询到内容会有异常,不会返回null
Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
- 解决上面抛出异常问题,使用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));
}
}