在springboot中使用jdbcTemplate

有时候在springboot中使用jdbcTemplate比用mybatis更灵活。

一、首先在application.properties中定义DataSource的参数

spring.datasource.dynamic.datasource.pressure1.username=uuu
spring.datasource.dynamic.datasource.pressure1.password=ppp
spring.datasource.dynamic.datasource.pressure1.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.dynamic.datasource.pressure1.url=jdbc:sqlserver://ip:port;DatabaseName=dbname
spring.datasource.dynamic.datasource.pressure1.hikari.connection-timeout=60000
spring.datasource.dynamic.datasource.pressure1.hikari.minIdle=10
spring.datasource.dynamic.datasource.pressure1.hikari.maxPoolSize=20
spring.datasource.dynamic.datasource.pressure1.hikari.isAutoCommit=true
spring.datasource.dynamic.datasource.pressure1.hikari.idle-timeout=600000
spring.datasource.dynamic.datasource.pressure1.hikari.max-lifetime=28740000
spring.datasource.dynamic.datasource.pressure1.hikari.connection-test-query=SELECT 1

二、定义数据源配置类

 

@Configuration
public class DataSourceConfig {

@Bean(name= "pressure1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.dynamic.datasource.pressure1")
    public DataSource pressure1DataSource() {
        DruidDataSource build = DruidDataSourceBuilder.create().build();
        return build;
    }


@Bean(name="pressure1Template")
    public JdbcTemplate pressure1Template (
            @Qualifier("pressure1DataSource")  DataSource dataSource ) {
        return new JdbcTemplate(dataSource);
    }

}

三、然后就可以愉快的用了

@Service
public class StateServiceImpl implements StateService {


    @Autowired
    @Qualifier("pressure1Template")
    private JdbcTemplate jdbcTemplate1;

   @Override
    public List<State> selectAll() {
        String sql = "select id,name from table_name";
        RowMapper<State> rowMapper = new RowMapper<State>() {
            @Override
            public StatInf mapRow(ResultSet rs, int i) throws SQLException {
                State state = new State();
                statInf.setId(rs.getString("ID"));
                statInf.setName(rs.getString("name"));
                return state;
            }
        };
        List<State> state1 = jdbcTemplate1.query(sql, rowMapper);
       return statInfs1 

}

}

 

在springboot中使用jdbcTemplate

上一篇:启动Canal-adapter 1.1.5 日志报错,Mysql 数据库连接 Communications link failure,问题处理


下一篇:SQL中,关于int型数据取值长度的问题