整合jdbc,Druid

对于数据访问层,无论是SQL还是NOSQL,Springboot底层都是采用Spring Data的方式进行统一处理。

整合jdbc

1、新建项目引入web模块和连接mysql必须的模块,JDBC API,MySQL Driver

2、项目建立完成后,发现已经替我们导入响应的启动器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 <!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

3、编写yaml配置文件连接数据库

1
2
3
4
5
6
spring:
datasource:
username: root
password: 2824199842
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver

在测试类中测试连接是否成功

4、配置完这一些东西后,我们就可以直接去使用了,因为SpringBoot已经默认帮我们进行了自动配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@SpringBootTest
class Springboot04DataApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
// 查看默认数据源 据说是最快的数据库连接池 HikariDataSource
System.out.println(dataSource.getClass());
// 获取数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
// 关闭连接
connection.close();
}
}

5、编写一个Controller,注入 jdbcTemplate,编写测试方法进行访问测试;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@RestController // 返回json对象给浏览器
public class JDBCController {
/**
* springboot对原生jdbc做了轻量级的封装
* 并且通过JdbcTemplate类提供了对数据库的crud操作
*
* execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
* update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;
* batchUpdate方法用于执行批处理相关语句;
* query方法及queryForXXX方法:用于执行查询相关语句;
* call方法:用于执行存储过程、函数相关语句
*/
@Autowired
private JdbcTemplate jdbcTemplate;
// 查询数据库中员工表的所有记录
// 没有实体类,从数据库查询到的数据怎么封装? 使用万能的Map!
@GetMapping("listAllUser")
public List<Map<String,Object>> listAllUser(){
// 原生jdbc操作
String sql = "select * from user";
List<Map<String, Object>> allUser = jdbcTemplate.queryForList(sql);
return allUser;
}

@GetMapping("/addUser")
public String addUser(){
String sql = "insert into user(name,pwd)value('wd1','123456')";
jdbcTemplate.update(sql);
return "addOK";
}

@GetMapping("/deleteUser/{id}") //@PathVariable接收路径中占位符的值
public String deleteUser(@PathVariable("id") int id){
String sql = "delete from user where id=?";
jdbcTemplate.update(sql,id);
return "deleteOK";
}

@GetMapping("/updateUser/{id}")
public String updateUser(@PathVariable("id") int id){
String sql = "update user set name=?,pwd=? where id="+id;
// 封装
Object[] objects = new Object[2];
objects[0]="张伟";
objects[1]="666666";
jdbcTemplate.update(sql,objects);
return "updateOK";
}
}

至此,使用原生的jdbc完成了基本的crud操作,因为springboot对jdbc进行了轻量级的封装,在使用上也并不是很繁琐。

整合Druid

1、添加Druid依赖

1
2
3
4
5
6
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>

2、在配置文件中指定数据源

1
2
3
4
5
6
7
spring:
datasource:
username: root
password: 2824199842
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource # 自定义数据源

3、测试并查看数据源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@SpringBootTest
class Springboot04DataApplicationTests {

@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());//class com.alibaba.druid.pool.DruidDataSource
// 获取数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
// 关闭连接
connection.close();
}
}

4、获取连接成功后,可以设置数据源连接初始化大小、最大连接数、等待时间、最小连接数等设置项

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
spring:
datasource:
username: root
password: 2824199842
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource # 自定义数据源

#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
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,stat:监控统计、log4j:日志记录、wall:防御sql注入
#需要导入 log4j 依赖
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

5、导入log4j依赖

1
2
3
4
5
6
<!--log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>

6、创建DruidConfig类,用于拓展配置druid

将数据源的配置文件绑定到容器中,无需springboot再创建容器

1
2
3
4
5
6
7
8
9
10
11
12
13
@Configuration
public class DruidConfig {
/**
*将自定义的Druid数据源添加到容器中,不再让Spring Boot自动创建
*绑定全局配置文件中的druid数据源属性到DruidDataSource从而让它们生效
* @return
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource druidDataSource(){
return new DruidDataSource();
}
}

配置后台监控功能:
Druid 数据源具有监控的功能,并提供了一个 web 界面方便用户查看,类似安装路由器 时,人家也提供了一个默认的 web 页面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Bean // 注入到容器中,就相当于web.xml文件
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean =
new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// 配置后台登录名和密码
Map<String, String> initParameters = new HashMap<String, String>();
// 增加配置
initParameters.put("loginUsername","admin");// loginUsername loginPassword是固定的
initParameters.put("loginPassword","123456");
// 访问权限
initParameters.put("allow","");
// 设置初始化参数
bean.setInitParameters(initParameters);
return bean;
}

访问http://localhost:8080/druid/

登录成功后

配置过滤器

1
2
3
4
5
6
7
8
9
10
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
// 设置过滤请求
HashMap<String, String> initParameters = new HashMap<>();
initParameters.put("exclusion","*.js,*.css,/druid/*");// 设置不进行过滤的资源
bean.setInitParameters(initParameters);
return bean;
}