上周学习了SpringBoot项目的基本结构已经配置文件的一些使用,其实不用特意去记住这些配置及内容,只是需要学习一下有这样一个印象,当工作中有疑惑的时候能够有思路,能够想到解决问题的原因就可以了,这篇文章更是如此,这篇文章我会列一下我在工作中常用的SpringBoot集成框架,并将一些内容简单讲解,当我们工作中发现项目也集成了该框架,我们可以第一时间知道这个框架是用来做什么的,甚至直接可以拿来使用就最好不过了,介绍到此结束,接下来开始正文。
SpringBoot集成JDBC
1.导入依赖
<!-- SpringBootWeb开发的启动器(必须引入,否则项目都无法启动)-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JDBC的启动器(用于进行数据库连接,同Mybatis)-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2.配置文件
server:
port: 8000
jdbc:
driver-class-name: com.mysql.cj.jdbc.Driver #Mysql 6以上的版本使用com.mysql.cj.jdbc.Driver,Mysql 6以下版本使用com.mysql.jdbc.Driver
username: 用户名
password: "密码"
#Mysql地址,后面为连接信息配置,不用改变
url: jdbc:mysql://数据库服务器IP/阿里云数据库则为云地址:端口号/数据库名称?autoReconnect=true&useUnicode=true&characterEncoding=UTF8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&allowMultiQueries=true
3.JDBC创建Bean对象
package com.springBoot.helloworld.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**
* @author Me
* @date 2022/3/27 1:21
*/
@Configuration
public class MyJdbcTemplate {
@Value("${jdbc.driver-class-name}")
private String driverClassName;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public JdbcTemplate myFirstJdbcTemplate(){
DriverManagerDataSource dataSource=new DriverManagerDataSource();
dataSource.setDriverClassName(this.driverClassName);
dataSource.setUrl(this.url);
dataSource.setUsername(this.username);
dataSource.setPassword(this.password);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.setQueryTimeout(1000);
return jdbcTemplate;
}
}
4.JDBC使用
package com.springBoot.helloworld.controller.test1;
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.RestController;
/**
* @author Me
* @date 2022/3/19 15:14
*/
@RestController
public class springBootController {
// 使用JDBC需要根据名称注入对应的依赖,注意名称要使用添加Bean注解的方法名称
@Autowired
private JdbcTemplate myFirstJdbcTemplate;
@GetMapping("/index")
public String test() {
String sql = "select * from student";
System.out.println(myFirstJdbcTemplate.queryForList(sql));
return "helloworld";
}
}
使用这种方式就可以进行JDBC的连接了,我只尝试了连接Mysql数据库,如果需要连接其他的数据库,例如Oracle、SqlServer等数据库的话,还是需要小伙伴们自行尝试哈。
我们也可以这样使用,这是在我项目中的使用方式,就是将JDBC数据库的连接信息统一放在spring-dataSource配置下。
此时的配置文件为:
server:
port: 8000
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver #Mysql6以上的版本使用com.mysql.cj.jdbc.Driver,Mysql6以下版本使用com.mysql.jdbc.Driver
username: 用户名
password: "密码"
#Mysql地址,后面为连接信息配置,不用改变
url: jdbc:mysql://数据库服务器IP/阿里云数据库则为云地址:端口号/数据库名称?autoReconnect=true&useUnicode=true&characterEncoding=UTF8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&allowMultiQueries=true
jdbc:
driver-class-name: com.mysql.cj.jdbc.Driver #Mysql6以上的版本使用com.mysql.cj.jdbc.Driver,Mysql6以下版本使用com.mysql.jdbc.Driver
username: 用户名
password: "密码"
#Mysql地址,后面为连接信息配置,不用改变
url: jdbc:mysql://数据库服务器IP/阿里云数据库则为云地址:端口号/数据库名称?autoReconnect=true&useUnicode=true&characterEncoding=UTF8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&allowMultiQueries=true
JDBC的Java配置文件为:
package com.springBoot.helloworld.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
/**
* @author Me
* @date 2022/3/27 1:21
*/
@Configuration
public class MyJdbcTemplate {
// value注解添加 spring.datasource 前缀
@Value("${spring.datasource.jdbc.driver-class-name}")
private String driverClassName;
@Value("${spring.datasource.jdbc.url}")
private String url;
@Value("${spring.datasource.jdbc.username}")
private String username;
@Value("${spring.datasource.jdbc.password}")
private String password;
@Bean
public JdbcTemplate myFirstJdbcTemplate(){
DriverManagerDataSource dataSource=new DriverManagerDataSource();
dataSource.setDriverClassName(this.driverClassName);
dataSource.setUrl(this.url);
dataSource.setUsername(this.username);
dataSource.setPassword(this.password);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.setQueryTimeout(1000);
return jdbcTemplate;
}
}
这样做的好处就在于将数据库连接信息全部放在spring.datasource下面,方便统一管理。
一般我们在工作中使用Mybatis去连接数据库,更有新的工程是使用Mybatis-Plus强化Mybatis的功能,不太会使用JDBC了,但是JDBC会用于我们的项目可能需要连接多个数据库的时候使用
SpringBoot整合Druid数据库连接池
Druid连接池是阿里出品的,功能十分强大,下面简单给大家介绍一个小功能,你就能看出他的强大了,首先第一步还是导入依赖。
<!-- druid数据库连接池(用于对数据库连接进行管理)-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.1</version>
</dependency>
第二步编写配置文件
server:
port: 8000
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver #Mysql6以上的版本使用com.mysql.cj.jdbc.Driver,Mysql6以下版本使用com.mysql.jdbc.Driver
username: 用户名
password: "密码"
#Mysql地址,后面为连接信息配置,不用改变
url: jdbc:mysql://数据库服务器IP/阿里云数据库则为云地址:端口号/数据库名称?autoReconnect=true&useUnicode=true&characterEncoding=UTF8&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true&allowMultiQueries=true
# 配置类型为Druid数据库连接池
type: com.alibaba.druid.pool.DruidDataSource
# 初始化大小
# initialization: 5
# minIdle: 5
# maxActive: 20
# maxWait: 60000
# timeBetweenEvictionRunsMillis: 60000
# minEvictableIdleTimeMillis: 300000
# validationQuery: SELECT 1 FROM DUAL
# testWhileIdle: true
# testOnBorrow: false
# testOnReturn: false
# poolPreparedStatements: true
# 配置监控统计拦截的过滤器:stat监控统计、wall防御SQL注入、log4j日志记录
# 使用log4j需要导入依赖,导入后修改该键值对为filters:stat,wall,log4j
filters: stat,wall
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;durid.stat.slowSqlMillis=500
如果监听时需要log4j日志记录则导入依赖(我测试过了,添加log4j没有什么大的变化,哈哈,尤其是今年年初log4j爆出了安全漏洞,比较抵触,但是个人练习用的话没什么问题)
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
第三步是编写Java配置类
package com.springBoot.helloworld.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
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;
/**
* @author Me
* @date 2022/3/27 11:57
*/
@Configuration
public class DruidConfig {
@ConfigurationProperties(value = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
@Bean
public ServletRegistrationBean servletRegistrationBean() {
// 配置后台SQL管理页面,访问localhost:端口号/druid/即访问
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
HashMap<String, String> initMap = new HashMap<>();
// 页面登录账号
initMap.put("loginUsername", "admin");
initMap.put("loginPassword", "123456");
// 允许谁能访问
initMap.put("allow", "");
// 禁止谁能访问
// initMap.put("用户名", "IP地址");
bean.setInitParameters(initMap);
return bean;
}
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
// 可以过滤哪些请求
HashMap<String, String> initMap = new HashMap<>();
// 这些内容不进行统计
initMap.put("exclusions", "*.js, *.css, /druid/*");
bean.setInitParameters(initMap);
return bean;
}
}
后台管理页面是这个样子滴
Druid数据库连接池的功能真滴很强大,但是其实在我工作的项目中并没有使用Druid,原因在于Druid功能多,但性能不强,目前还是使用HikariCP的连接池,Spring官方推荐的也是这个,他的功能少,但性能强大。
公司中一般不使用个人主机作为数据库,而是使用阿里云的云数据库,这种数据库自带SQL治理功能,慢SQL查询,指定SQL查询等功能,所以数据库连接池应该专心的做好本职工作,因此性能的重要就提升到了第一位,这也是选择HikariCP的原因。
HikariCP
HikariCP没有Druid那么多功能,就只是单纯本分的数据库连接池,哈哈。
给大家简单介绍一下HikariCP的配置:
# 文件配置
spring:
datasource:
# 配置类型为HikariCP数据库连接池
type: com.zaxxer.hikari.HikariDataSource
hikari:
minimum-idle: 2 #池中最小的空闲线程数
connection-timeout: 2000 #连接超时时长,小于250则重置为30000
maximum-pool-size: 200 #池中最大连接数
auto-commit: true #是否自动提交,默认true
data-source-properties:
cachePrepStmts: true #是否自定义配置 为true下面才生效
prepStmtCacheSize: 250 #连接池大小,默认25,官方推荐250-500
prepStmtCacheSqlLimit: 2048 #单条语句最大长度默认256,官方推荐2048
useServerPrepStmts: true #新版本MySQL支持服务器端准备,开启能够得到显著性能提升
SpringBoot整合Mybatis
1.首先导入依赖
<!-- 整合Mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
2.编写Java使用类
Mybatis的使用要借助于mapper接口及mapperXML文件,项目结构一般为
2-1编写mapper接口
package com.springBoot.helloworld.mapper;
import com.springBoot.helloworld.pojo.Person;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* @author Me
* @date 2022/3/27 13:51
*/
// 需要添加Mapper注解表明是一个mapper接口
// 也可以不添加此注解,在启动类上添加@MapperScan("com.springBoot.helloworld.mapper")注解
// @MapperScan可以指定扫描的包同样可以实现此效果
@Mapper
public interface StudentMapper {
public List<Person> queryMyList();
}
2-2编写XML文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.springBoot.helloworld.mapper.StudentMapper">
<!-- 此文件可以复制,但namespace需要自己定义,格式为自己项目的mapper全路径-->
<select id="queryMyList" resultType="com.springBoot.helloworld.pojo.Person">
select name, age, class as myClass from student
</select>
</mapper>
3.编写配置文件
使用mybatis的时候不需要过多的配置,只需要配置mapper接口与XML文件的映射关系
# 表示mybatis会在如下两个路径中查询对应的XML文件,超出此范围则查询不到
mybatis:
mapper-locations:
- classpath:mapper/*Mapper.xml #表示匹配resource目录下的mapper目录下的所有Mapper.xml结尾的文件
- classpath:mapper/*/*Mapper.xml #表示匹配resource目录下的mapper目录下的所有目录下的所有Mapper.xml结尾的文件
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #表示打印SQL执行的log日志
如果不配置就会发生org.apache.ibatis.binding.BindingException报错。
到这里就可以自由使用Mybatis了,下面给小伙伴推荐一下以往的Mybatis的文章,供大家学习借鉴,如果有问题的话随时可以私信问我哦。
我工作时的项目选择的是Mybatis-Plus作为持久层的框架,Mybatis-Plus是Mybatis的强化版,有兴趣或有时间的小伙伴们,我建议也去学习一下,完整版教学这里放上链接↓
最后推荐几个我在工作中感觉比较好用的Mybatis的小插件
1.Mybatis Builder
这个插件的用处很小,但很精妙
使用这个插件以后,我们的mapper接口与xml文件的旁边就会生成一个绿色的箭头,此时我们就可以点击箭头进行mapper接口与xml文件的跳转,个人感觉很好用,用过才知道。
2.Mybatis log
这个插件需要在网上下载后自行导入,因为新版本的是需要收费的哈哈,这个到底有多好用呢?
如果没有这个插件,我们想看一下真实执行的SQL需要查看控制台
如果SQL有多个参数的时候就需要自己组装,但是这个插件会显示出完整的SQL打印内容
我们就可以直接复制出来使用了。
需要这个插件的小伙伴可以私聊我获取哈。
下一篇请戳↓