springboot整合jdbc使用
一:springboot整合jdbc需要的配置
1.pom.xml文件配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2.application.yaml文件配置
spring:
thymeleaf:
cache: false
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
3.测试数据库连接成功的两种方法
(1)在test测试类中
@SpringBootTest
class SpringbootApplicationTests {
@Autowired
DataSource dataSource;
@Test
public void contextLoads() throws SQLException{
//查看默认的数据源
System.out.println(dataSource.getClass());
//获取数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
// xxxx Template :SpringBoot已经配置好模板bean,拿来急用CRUD
//关闭
connection.close();
}
}
(2)使用右侧的数据库连接
如果你遇到下面的情况,原因是MySQL驱动中默认时区是UTC,与本地时间(中国)相差八个小时,所以链接不上
解决方法:
- 点开最右侧 Advanced,找到 serverTimezone,在右侧value处填写 GMT,保存即可!(或填写 Asia/Shanghai)
- 测试连接
成功!
二:使用jdbc对数据库进行增删查改
package com.example.springboot.controller;
import org.omg.CORBA.Object;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class JDBCController {
@Autowired
JdbcTemplate jdbcTemplate;
//查询数据库的所有信息
//没有实体类,数据库中的东西,怎获取
@GetMapping("/userList")
public List<Map<String,java.lang.Object>> userList(){
String sql = "select * from iot_alarm_info";
List<Map<String, java.lang.Object>> list_test = jdbcTemplate.queryForList(sql);
return list_test;
}
@GetMapping("/addAlarm")
public List<Map<String, java.lang.Object>> addList(){
String sql = "insert into zcpower.iot_alarm_info(id,name,sensor_id) values(8,'测试123444',3)";
jdbcTemplate.update(sql);
String select_sql = "select * form iot_alarm_info";
List<Map<String, java.lang.Object>> queryForList = jdbcTemplate.queryForList(select_sql);
return queryForList;
}
@GetMapping("/updateAlarm/{id}")
public String updateAalarm(@PathVariable("id") int id){
String sql = "update zcpower.iot_alarm_info set name=?,sensor_id=? where id="+id;
Object[] objects = new Object[2];
// objects[0] = "小明";
// objects[1] = "11";
jdbcTemplate.update(sql, "wangc",1);
return "upodatye-ok";
}
@GetMapping("/deleteAlarm/{id}")
public String deleteList(@PathVariable("id") int id){
String sql = "delete from zcpower.iot_alarm_info where id=?";
jdbcTemplate.update(sql,id);
return "succss";
}
}
三:springboot整合Druid
1.简介Druid:
Druid是阿里开源平台上一个数据库连接池实现,结合了C3P0、DBCP、PROXOOL等DB池的有点,同时加入如了日志监控,
Druid可以很好的监控DB池连接和SQL的执行情况,天生就是针对监控而生的 DB连接池。
2.配置
<!-- Druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.4</version>
</dependency>
配置applicaion.yml文件
spring:
datasource:
url: jdbc:mysql://localhost:3306/store?serverTimezone=UTC&useUnicode=true&characterEcoding=utf-8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
# springboot默认是不注入这些属性的
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
type: com.alibaba.druid.pool.DruidDataSource
3.代码配置
在config层配置
package com.example.springboot.Config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.HashMap;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
//后台监控
@Bean
public ServletRegistrationBean<StatViewServlet> StatViewServlet(){
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// 后台登陆需要账号、密码
HashMap<String,String> initParameters = new HashMap<>();
//增加配置
initParameters.put("loginUsername","admin"); //登录Key 是固定的loginUsername loginPassword
initParameters.put("loginPassword","12345");
//允许谁可以访问
initParameters.put("allow",""); //允许所有人
//禁止访问
// initParameters.put("kuangsheng","192.168.1.123");
bean.setInitParameters(initParameters);
return bean;
}
//filter
public FilterRegistrationBean<javax.servlet.Filter> webSataFilter(){
FilterRegistrationBean<javax.servlet.Filter> bean = new FilterRegistrationBean<>();
HashMap<String,String> initParameters = new HashMap<>();
//可以过滤掉那些东西
initParameters.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParameters);
return bean;
}
}
配置完毕后,我们可以选择访问 :http://localhost:8080/druid/login.html
使用你自定义的账户和密码,登录进入,出现以下界面成功