演示 Spring Boot 如何通过 jdbc+HikariDataSource 完成对 Mysql 操作
说明:
-- 创建数据库 spring_boot
DROP DATABASE IF EXISTS spring_boot;
CREATE DATABASE spring_boot;
USE spring_boot;
-- 创建家居表
CREATE TABLE furn(
`id` INT(11) PRIMARY KEY AUTO_INCREMENT, ## id
`name` VARCHAR(64) NOT NULL, ## 家居名
`maker` VARCHAR(64) NOT NULL, ## 厂商
`price` DECIMAL(11,2) NOT NULL, ## 价格
`sales` INT(11) NOT NULL, ## 销量
`stock` INT(11) NOT NULL, ## 库存
`img_path` VARCHAR(256) NOT NULL ## 照片路径
);
-- 初始化家居数据
INSERT INTO furn(`id` , `name` , `maker` , `price` , `sales` , `stock` , `img_path`)
VALUES(NULL , '北欧风格小桌子' , '熊猫家居' , 180 , 666 , 7 ,
'assets/images/product-image/1.jpg');
INSERT INTO furn(`id` , `name` , `maker` , `price` , `sales` , `stock` , `img_path`)
VALUES(NULL , '简约风格小椅子' , '熊猫家居' , 180 , 666 , 7 ,
'assets/images/product-image/2.jpg');
INSERT INTO furn(`id` , `name` , `maker` , `price` , `sales` , `stock` , `img_path`)
VALUES(NULL , '典雅风格小台灯' , '蚂蚁家居' , 180 , 666 , 7 ,
'assets/images/product-image/3.jpg');
INSERT INTO furn(`id` , `name` , `maker` , `price` , `sales` , `stock` , `img_path`)
VALUES(NULL , '温馨风格盆景架' , '蚂蚁家居' , 180 , 666 , 7 ,
'assets/images/product-image/4.jpg');
SELECT * FROM furn;
参考官方文档 ==> 文档链接
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-jdbcartifactId>
dependency>


<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.49version>
dependency>
spring:
datasource: #配置数据源
# 说明:如果没有指定 useSSL=true , 启动项目会有报红警告
url: jdbc:mysql://localhost:3306/spring_boot?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: hsp
driver-class-name: com.mysql.jdbc.Driver
package com.xjs.springboot.bean;
import java.math.BigDecimal;
/**
* @Author: 谢家升
* @Version: 1.0
*/
public class Furn {
private Integer id;
private String name;
private String maker;
private BigDecimal price;
private Integer sales;
private Integer stock;
private String imgPath = "assets/images/product-image/1.jpg";
public Furn(Integer id, String name, String maker, BigDecimal price, Integer sales, Integer stock, String imgPath) {
this.id = id;
this.name = name;
this.maker = maker;
this.price = price;
this.sales = sales;
this.stock = stock;
this.imgPath = imgPath;
}
public Furn() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMaker() {
return maker;
}
public void setMaker(String maker) {
this.maker = maker;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public Integer getSales() {
return sales;
}
public void setSales(Integer sales) {
this.sales = sales;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
public String getImgPath() {
return imgPath;
}
public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}
@Override
public String toString() {
return "Furn{" +
"id=" + id +
", name='" + name + '\'' +
", maker='" + maker + '\'' +
", price=" + price +
", sales=" + sales +
", stock=" + stock +
", imgPath='" + imgPath + '\'' +
'}';
}
}
package com.xjs.springboot;
import com.xjs.springboot.bean.Furn;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: 谢家升
* @Version: 1.0
*
* 这里演示一下 如何在springboot中开发测试类
*/
@SpringBootTest
public class ApplicationTests {
//回顾一下 => spring 的 JdbcTemplate
@Resource
private JdbcTemplate jdbcTemplate;
@Test
public void contextLoads() {
BeanPropertyRowMapper<Furn> rowMapper = new BeanPropertyRowMapper<>(Furn.class);
List<Furn> furns = jdbcTemplate.query("SELECT * FROM `furn`", rowMapper);
for (Furn furn : furns) {
System.out.println(furn);
}
//看看底层使用的是什么数据源类型[HikariDataSource]
System.out.println(jdbcTemplate.getDataSource().getClass());
//com.zaxxer.hikari.HikariDataSource
}
}

HiKariCP:目前市面上非常优秀的数据源,是 springboot2 默认数据源
Druid:性能优秀,Druid 提供性能卓越的连接池功能外【Java 基础】,还集成了 SQL 监控,黑名单拦截等功能,强大的监控特性,通过 Druid 提供的监控功能,可以清楚知道连接池和 SQL 的工作情况,所以根据项目需要,我们也要掌握 Druid 和 SpringBoot 整合
整合 Druid 到 Spring-Boot 方式
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.17version>
dependency>
package com.xjs.springboot.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* @Author: 谢家升
* @Version: 1.0
*
* DruidDataSourceConfig -配置类
*/
@Configuration
public class DruidDataSourceConfig {
//编写方法,注入DruidDataSource
/**为什么我们注入了自己的DataSource , 原来的 HikariDataSource就失效了呢??
1. 默认的数据源是如何配置的? @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
通过 @ConditionalOnMissingBean({ DataSource.class}) 判断如果容器有 DataSource Bean 就不注入默认的 HikariDataSource
2. debug 源码
*/
@ConfigurationProperties("spring.datasource")
@Bean
public DataSource dataSource() {
//1. 配置了 @ConfigurationProperties("spring.datasource")
// 就可以读取到 application.yml 的配置
//2. 我们就不需要调用 DruidDataSource 对象的 setXXX() , 会自动关联调用
DruidDataSource druidDataSource = new DruidDataSource();
//druidDataSource.setUsername();
//druidDataSource.setPassword();
//druidDataSource.setUrl();
return druidDataSource;
}
}






package com.xjs.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.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* @Author: 谢家升
* @Version: 1.0
*
* DruidDataSourceConfig -配置类
*/
@Configuration
public class DruidDataSourceConfig {
//编写方法,注入DruidDataSource
/**
* 为什么我们注入了自己的DataSource , 原来的 HikariDataSource就失效了呢??
* 1. 默认的数据源是如何配置的? @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
* 通过 @ConditionalOnMissingBean({ DataSource.class}) 判断如果容器有 DataSource Bean 就不注入默认的 HikariDataSource
* 2. debug 源码
*/
@ConfigurationProperties("spring.datasource")
@Bean
public DataSource dataSource() {
//1. 配置了 @ConfigurationProperties("spring.datasource")
// 就可以读取到 application.yml 的配置
//2. 我们就不需要调用 DruidDataSource 对象的 setXXX() , 会自动关联调用
DruidDataSource druidDataSource = new DruidDataSource();
//druidDataSource.setUsername();
//druidDataSource.setPassword();
//druidDataSource.setUrl();
return druidDataSource;
}
//配置druid的监控功能
@Bean
public ServletRegistrationBean statViewServlet() {
//创建 StatViewServlet
StatViewServlet statViewServlet = new StatViewServlet();
ServletRegistrationBean<StatViewServlet> registrationBean =
new ServletRegistrationBean<>(statViewServlet, "/druid/*");
//设置 init-parameter , 设置用户名和密码
registrationBean.addInitParameter("loginUsername", "xjs");
registrationBean.addInitParameter("loginPassword", "123456");
return registrationBean;
}
}



package com.xjs.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.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.sql.SQLException;
/**
* @Author: 谢家升
* @Version: 1.0
*
* DruidDataSourceConfig -配置类
*/
@Configuration
public class DruidDataSourceConfig {
//编写方法,注入DruidDataSource
/**
* 为什么我们注入了自己的DataSource , 原来的 HikariDataSource就失效了呢??
* 1. 默认的数据源是如何配置的? @ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
* 通过 @ConditionalOnMissingBean({ DataSource.class}) 判断如果容器有 DataSource Bean 就不注入默认的 HikariDataSource
* 2. debug 源码
*/
@ConfigurationProperties("spring.datasource")
@Bean
public DataSource dataSource() throws SQLException {
//1. 配置了 @ConfigurationProperties("spring.datasource")
// 就可以读取到 application.yml 的配置
//2. 我们就不需要调用 DruidDataSource 对象的 setXXX() , 会自动关联调用
DruidDataSource druidDataSource = new DruidDataSource();
//druidDataSource.setUsername();
//druidDataSource.setPassword();
//druidDataSource.setUrl();
//加入监控功能
druidDataSource.setFilters("stat");
return druidDataSource;
}
//配置druid的监控功能
@Bean
public ServletRegistrationBean statViewServlet() {
//创建 StatViewServlet
StatViewServlet statViewServlet = new StatViewServlet();
ServletRegistrationBean<StatViewServlet> registrationBean =
new ServletRegistrationBean<>(statViewServlet, "/druid/*");
//设置 init-parameter , 设置用户名和密码
registrationBean.addInitParameter("loginUsername", "xjs");
registrationBean.addInitParameter("loginPassword", "123456");
return registrationBean;
}
}
package com.xjs.springboot.controller;
import com.xjs.springboot.bean.Furn;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: 谢家升
* @Version: 1.0
*/
@Controller
public class DruidSqlController {
@Resource
private JdbcTemplate jdbcTemplate;
@ResponseBody
@GetMapping("/sql")
public List<Furn> crudDB() {
BeanPropertyRowMapper<Furn> rowMapper = new BeanPropertyRowMapper<>(Furn.class);
List<Furn> furns = jdbcTemplate.query("select * from furn", rowMapper);
for (Furn furn : furns) {
System.out.println(furn);
}
return furns;
}
}



//配置webStatFilter , 用于采集web-jdbc关联的监控数据
@Bean
public FilterRegistrationBean webStatFilter() {
//创建WebStatFilter
WebStatFilter webStatFilter = new WebStatFilter();
FilterRegistrationBean<WebStatFilter> filterRegistrationBean =
new FilterRegistrationBean<>(webStatFilter);
//默认对所有的 url请求 进行监控
filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
//排除指定的 url
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}













<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.17version>
dependency>

spring:
servlet:
multipart:
max-file-size: 10MB # 表示单个文件上传最大 10MB
max-request-size: 50MB # 表示一次请求上传多文件最多上传 10MB
datasource: #配置数据源
# 说明:如果没有指定 useSSL=true , 启动项目会有报红警告
url: jdbc:mysql://localhost:3306/spring_boot?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: hsp
driver-class-name: com.mysql.jdbc.Driver
# 配置druid 和 监控功能
druid:
stat-view-servlet:
enabled: true
login-username: xjs
login-password: 888
reset-enable: false
web-stat-filter: #配置web监控
enabled: true
url-pattern: /*
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
filter:
stat: #配置sql监控
slow-sql-millis: 1000
log-slow-sql: true
enabled: true
wall: #配置sql防火墙
enabled: true
config:
drop-table-allow: false #不允许修改表
select-all-column-allow: false #不允许执行SELECT * FROM T这样的语句

