【Springboot】多数据源配置使⽤jdbcTemplate执⾏SQL 数据源配置⽂件
# 多数据源配置
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(){
ate().build();
jdbctemplate查询一条数据}
@Bean(name ="dataSource2")
@Qualifier("dataSource2")
@ConfigurationProperties(prefix="spring.datasource.ds2")
public DataSource secondaryDataSource(){
ate().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
2. 查询⼀条记录,注意:queryForObject 没有查询到内容会有异常,不会返回null Integer count = jdbcTemplate.queryForObject(sql,Integer.class);
3. 解决上⾯抛出异常问题,使⽤query
List<byte[]> list = jdbcTemplate.query(sql,new BytesRowMapper());
if(list.size()==0){
return null;
}else{
(0);
}
public class BytesRowMapper implements RowMapper<byte[]>{
@Override
public byte[]mapRow(ResultSet resultSet,int i)throws SQLException {
Bytes(1);
}
}
⾃定义rowMapper为所欲为,随便映射查询结果到⾃⼰定义的类
public class StateRowMapper implements RowMapper<PGState>{
@Override
public State mapRow(ResultSet resultSet,int i)throws SQLException {
return new String(1),String(2),Timestamp(3)); }
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。