SpringBoot集成JdbcTemplate

SpringBoot集成JdbcTemplate

一、环境搭建

开发工具:Spring Tool Suite v_3.9.3(简称STS)

依赖包管理(pom.xml):

<!-- 添加数据库依赖关系 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.0.25</version>
</dependency>

<!-- Oracle数据库支持 -->
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.1.0</version>
</dependency>

配置数据源

## 数据库配置
spring.datasource.driver-class-name = oracle.jdbc.driver.OracleDriver
spring.datasource.url = jdbc:oracle:thin:@136.6.161.200:1521:orcl
spring.datasource.username = cath_thinkops
spring.datasource.password = cath_thinkops#2018
package com.ustcinfo.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@PropertySource("classpath:application.properties") // 选择配置文件的来源
public class DruidDBConfig {

    @Autowired
    private Environment env; // SpringBoot会把扫描过后的值放到Environment中

    @Bean(name = "dataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username")); // 用户名
        dataSource.setPassword(env.getProperty("spring.datasource.password")); // 密码
        dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 'x' from dual");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}
二、使用

JdbcTemplate 使用,只要在类中注入即可:

@Autowired
private JdbcTemplate jdbcTemplate;

// 查询当前系统告警
public List<AlarmBord> queryAlarmBord() {
    String sql = "SELECT t.* FROM idc_alarm_bord t";
    return jdbcTemplate.query(sql, new BeanPropertyRowMapper<AlarmBord>(AlarmBord.class));
}

猜你喜欢

转载自blog.csdn.net/qq_35959573/article/details/80079857
今日推荐