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.info.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));
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值