在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 

}

}

 

posted @ 2021-05-17 19:53  Mars.wang  阅读(1175)  评论(0编辑  收藏  举报