数据库操作
JDBC + HikariDataSource
演示 Spring Boot 如何通过 jdbc+HikariDataSource 完成对 Mysql 操作。
应用实例
创建测试数据库和表
-- 创建 furns_ssm
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');
进行数据库开发,在 pom.xml 引入 data-jdbc starter。
<!--进行数据库开发,引入data-jdbc starter-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

Spring Boot 不知道项目要操作 Mysql 还是 Oracle,需要在 pom.xml 指定导入数据库 驱动, 并指定对应版本
<!--引入mysql的驱动
1. 这里没有使用版本仲裁 默认<mysql.version>8.0.26</mysql.version>
2. 指定的版本是5.1.49
-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
在 application.yml 配置操作数据源的信息
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 50MB
datasource: #配置数据源
# 说明: 如果你没有指定useSSL=true ,启动项目会报红警告
url: jdbc:mysql://localhost:3306/spring_boot?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
创建 src/main/java/com/lzw/springboot/bean/Furn.java
package com.lzw.springboot.bean;
import java.math.BigDecimal;
/**
* @author LiAng
*/
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 + '\'' +
'}';
}
}
修改 pom.xml
<!--如何要开发springboot测试类,我们需要引入 test starter-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
创建 src/test/java/com/lzw/springboot/ApplicationTests.java
package com.lzw.springboot;
import com.fasterxml.jackson.databind.BeanProperty;
import com.lzw.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 LiAng
* 如何在springboot开发测试类?
*/
@SpringBootTest
public class ApplicationTests {
@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);
}
//再次输出,看看底层使用的是什么数据源类型[class com.zaxxer.hikari.HikariDataSource]
System.out.println(jdbcTemplate.getDataSource().getClass());
}
}

整合 Druid 到 Spring-Boot
官方文档
https://github.com/alibaba/druid
基本介绍
HiKariCP:目前市面上非常优秀的数据源,是 springboot2 默认数据源 。
Druid: 性能优秀,Druid 提供性能卓越的连接池功能外,还集成了 SQL 监 控,黑名单拦截等功能,强大的监控特性,通过 Druid 提供的监控功能,可以清楚知道连接池和 SQL 的工作情况。
整合 Druid 到 Spring-Boot 方式
(1)自定义方式
(2)引入 starter 方式
Durid 基本使用
需求:将 Spring-Boot 的数据源切换成 Druid。
修改 pom.xml , 引入 druid 依赖
<!--引入druid依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.17</version>
</dependency>
创建 src/main/java/com/lzw/springboot/config/DruidDataSourceConfig.java
package com.lzw.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 LiAng
*/
@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.setUrl();
//druidDataSource.setUsername();
//druidDataSource.setPassword();
return druidDataSource;
}
}

Durid 监控功能-SQL 监控
https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98
修改 DruidDataSourceConfig.java
//配置druid的监控页功能
@Bean
public ServletRegistrationBean statViewServlet() {
StatViewServlet statViewServlet = new StatViewServlet();
ServletRegistrationBean<StatViewServlet> registrationBean =
new ServletRegistrationBean<>(statViewServlet,"/druid/*");
//设置init-parameter, 设置用户名和密码
registrationBean.addInitParameter("loginUsername", "lzw");
registrationBean.addInitParameter("loginPassword", "123456");
return registrationBean;
}
访问 http://localhost:10000/druid/index.html
不会被拦截


修改 DruidDataSourceConfig.java
@ConfigurationProperties("spring.datasource")
@Bean
public DataSource dataSource() throws SQLException {
DruidDataSource druidDataSource = new DruidDataSource();
//加入监控功能
druidDataSource.setFilters("stat");
return druidDataSource;
}
加入监控功能,参考 https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_StatFilter
创建 src/main/java/com/lzw/springboot/controller/DruidSqlController.java
模拟操作DB
package com.lzw.springboot.controller;
import com.lzw.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 LiAng
*/
@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;
}
}
浏览器请求 http://localhost:10001/sql
看监控页面

Durid 监控功能-Web 关联监控
文档:https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98

需求:配置 Web 关联监控配置:Web 应用、URI 监控
修改 DruidDataSourceConfig.java
//配置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;
}
修改 WebConfig.java
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
System.out.println("addInterceptors~~~");
//注册拦截器
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/","/login","/images/**","/upload.html","/upload","/sql");
}
};
}
浏览器请求 http://localhost:10001/sql

Durid 监控功能-SQL 防火墙
文档:https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98

修改 DruidDataSourceConfig.java
@ConfigurationProperties("spring.datasource")
@Bean
public DataSource dataSource() throws SQLException {
DruidDataSource druidDataSource = new DruidDataSource();
//加入监控功能, 加入了sql防火墙监控
druidDataSource.setFilters("stat,wall");
return druidDataSource;
}

Durid 监控功能-Session 监控
文档:https://github.com/alibaba/druid/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98
默认是打开的

此时先登录客户端,即可在监控页面中看到session信息

Druid Spring Boot Starter
基本介绍
- 前面使用的是引入 Druid+配置类 方式整合 Druid 和监控
- Druid Spring Boot Starter 可以让程序员在 Spring Boot 项目中更加轻松集成 Druid 和监控
文档
https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
应用实例
需求:使用 Druid Spring Boot Starter 方式完成 Druid 集成和监控
修改 pom.xml,注释掉
<!--引入druid依赖-->
<!--<dependency>-->
<!-- <groupId>com.alibaba</groupId>-->
<!-- <artifactId>druid</artifactId>-->
<!-- <version>1.1.17</version>-->
<!--</dependency>-->
注释掉整个 DruidDataSourceConfig.java
修改 pom.xml
<!--引入druid starter-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
修改 application.yml
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 50MB
datasource: #配置数据源
# 说明: 如果你没有指定useSSL=true ,启动项目会报红警告
url: jdbc:mysql://localhost:3306/spring_boot?useSSL=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
# 配置druid和监控功能
druid:
stat-view-servlet:
enabled: true
login-username: jack
login-password: 123
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 # 不允许查询所有字段的语句