目录
1.2:jabc的配置文件配置--application.yml
1.4:DataSourceInitializer:执行自定义建表sql语句
1.5:DataSourceInitializer:执行初始化插入sql语句
1.6:springboot使用JdbcTemplate来操作数据库
2.4:使用Druid数据源-利用web.xml配置druid的web监控和拦截器
2.5:使用Druid数据源-利用ServletRegistrationBean配置druid的web监控和拦截器
4.2:springboot使用SpringData JPA的流程
六:SpringBoot与数据访问
1:JDBC的配置和使用
1.1:创建jdbc环境
pom.xml文件如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
1.2:jabc的配置文件配置--application.yml
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://10.40.129.44:3306/test?serverTimezone=UTC
#com.mysql.jdbc.Driver 是5版本的驱动
#com.mysql。cj.jdbc.Driver 是8版本的驱动
#?serverTimezone=UTC 解决时区的报错
driver-class-name: com.mysql.jdbc.Driver
实验:
最终我们使用的配置是
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://10.40.129.44:3306/test?serverTimezone=UTC
#com.mysql.jdbc.Driver 是5版本的驱动
#com.mysql。cj.jdbc.Driver 是8版本的驱动
#?serverTimezone=UTC 解决时区的报错
driver-class-name: com.mysql.cj.jdbc.Driver
1.3:springboot链接数据库的原理
数据源的相关配置都在DataSourceProperties里面;ctrl+点击配置文件中刚才配置的属性就可以进入;
1:参考DataSourceConfiguration ,根据配置创建数据源,springboot2.x默认使用hikari数据源;可以使用spring.datasource.type指定自定义的数据源类型;
2:springboot默认支持的数据源有
org.apache.commons.dbcp2.BasicDataSource,
com.zaxxer.hikari.HikariDataSource
org.apache.tomcat.jdbc.pool.DataSource
3:如果使用spring.datasource.type来自定义数据源
使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
1.4:DataSourceInitializer:执行自定义建表sql语句
由他调用各种初始化方法
最终执行的是DataSourceInitializer的方法
1:所以要在系统开始的时候执行建表语句,必须在配置文件中配置
2:而建表语句的 文件名为:默认为:schema.sql,schema-all.sql;源代码设置在下面:
3:也可以在配置文件中指定建表语句sql的位置,源代码如下
设置如下:
1.5:DataSourceInitializer:执行初始化插入sql语句
和上边建表的设置一样
1:要不然设置插入sql语句的文件名默认为:schema.sql,schema-all.sql;源代码设置在下面:
2:要不然设置
1.6:springboot使用JdbcTemplate来操作数据库
JdbcTemplate将我们使用的JDBC的流程封装起来,包括了异常的捕捉、SQL的执行、查询结果的转换等等。spring大量使用Template Method模式来封装固定流程的动作,XXXTemplate等类别都是基于这种方式的实现。
除了大量使用Template Method来封装一些底层的操作细节,spring也大量使用callback方式类回调相关类别的方法以提供JDBC相关类别的功能,使传统的JDBC的使用者也能清楚了解spring所提供的相关封装类别方法的使用。
1:使用JdbcTemplate的execute()方法执行SQL语句
2:如果是UPDATE或INSERT,可以用update()方法。可以带参数防止sql注入
3:使用JdbcTemplate进行查询时,使用queryForXXX()等方法
例子:
//注入JdbcTemplate
@Autowired
JdbcTemplate jdbcTemplate;
@ResponseBody
@RequestMapping("/query")
public Map<String,Object> query(){
List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from department");
Map<String,Object> reslut = new HashMap<>();
reslut.put("date",maps);
return reslut;
}
结果是:
2、整合Druid数据源
Druid是一个关系型数据库连接池,它是阿里巴巴的一个开源项目。Druid支持所有JDBC兼容数据库,包括了Oracle、MySQL、PostgreSQL、SQL Server、H2等。Druid在监控、可扩展性、稳定性和性能方面具有明显的优势。通过Druid提供的监控功能,可以实时观察数据库连接池和SQL查询的工作情况。使用Druid连接池在一定程度上可以提高数据访问效率。
2.1:导入diuid依赖
<!-- 配置jdbc的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<!-- 配置mysql驱动的依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 导入druid数据源 -->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
2.2:在配置文件中配置配置数据源
由于springboot默认不支持druid数据源,需要配置type
和其它连接池一样DRUID的DataSource类为:com.alibaba.druid.pool.DruidDataSource,基本配置参数如下:
配置 | 缺省值 | 说明 |
name | 配置这个属性的意义在于,如果存在多个数据源,监控的时候可以通过名字来区分开来。 如果没有配置,将会生成一个名字,格式是:"DataSource-" + System.identityHashCode(this) | |
jdbcUrl | 连接数据库的url,不同数据库不一样。例如: mysql : jdbc:mysql://10.20.153.104:3306/druid2 oracle : jdbc:oracle:thin:@10.20.149.85:1521:ocnauto | |
username | 连接数据库的用户名 | |
password | 连接数据库的密码。如果你不希望密码直接写在配置文件中,可以使用ConfigFilter。详细看这里:https://github.com/alibaba/druid/wiki/%E4%BD%BF%E7%94%A8ConfigFilter | |
driverClassName | 根据url自动识别 | 这一项可配可不配,如果不配置druid会根据url自动识别dbType,然后选择相应的driverClassName(建议配置下) |
initialSize | 0 | 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 |
maxActive | 8 | 最大连接池数量 |
maxIdle | 8 | 已经不再使用,配置了也没效果 |
minIdle | 最小连接池数量 | |
maxWait | 获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置useUnfairLock属性为true使用非公平锁。 | |
poolPreparedStatements | false | 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。 |
maxOpenPreparedStatements | -1 | 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100 |
validationQuery | 用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会其作用。 | |
testOnBorrow | true | 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 |
testOnReturn | false | 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 |
testWhileIdle | false | 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 |
timeBetweenEvictionRunsMillis | 有两个含义: 1) Destroy线程会检测连接的间隔时间2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明 | |
numTestsPerEvictionRun | 不再使用,一个DruidDataSource只支持一个EvictionRun | |
minEvictableIdleTimeMillis | ||
connectionInitSqls | 物理连接初始化的时候执行的sql | |
exceptionSorter | 根据dbType自动识别 | 当数据库抛出一些不可恢复的异常时,抛弃连接 |
filters | 属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有: 监控统计用的filter:stat日志用的filter:log4j防御sql注入的filter:wall | |
proxyFilters | 类型是List<com.alibaba.druid.filter.Filter>,如果同时配置了filters和proxyFilters,是组合关系,并非替换关系 |
测试结果:
2.3:使用druid数据源-定制的数据源其他参数配置
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai
#com.mysql.jdbc.Driver 是5版本的驱动
#com.mysql。cj.jdbc.Driver 是8版本的驱动
#?serverTimezone=UTC 解决时区的报错
driver-class-name: com.mysql.cj.jdbc.Driver
# 设置此项,可以执行建表或者插入sql语句
# initialization-mode: always
# 指定建表sql的文件名,这是个集合,可以设置多个
# schema:
# - classpath:department.sql
# 插入数据sql文件位置,这也是一个集合
# data:
# - classpath:insert.sql
#配置druid数据源
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
#初始化连接池大小
initialSize: 5
#连接池最小活跃数
minIdle: 5
#连接池最大活跃数
maxActive: 20
#最大连接等待时间
maxWait: 60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
#配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
#验证连接有效与否的SQL,不同的数据配置不同
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
#里建议配置为TRUE,防止取到的连接不可用
testOnBorrow: false
testOnReturn: false
#打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,logback
#打开PSCache,并且指定每个连接上PSCache的大小
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
按照上述druid数据源的参数对数据源进行配置
在Spring Boot中驱动配置信息没有问题,但是连接池的配置信息不再支持这里的配置项,即无法通过配置项直接支持相应的连接池;这里列出的这些配置项可以通过定制化DataSource来实现。
目前Spring Boot中默认支持的连接池有dbcp,dbcp2, tomcat, hikari三种连接池。
由于Druid暂时不在Spring Bootz中的直接支持,故需要进行配置信息的定制:
效果如图:
2.4:使用Druid数据源-利用web.xml配置druid的web监控和拦截器
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DruidStatView</servlet-name>
<url-pattern>/druid/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>druidWebStatFilter</filter-name>
<filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
<init-param>
<param-name>exclusions</param-name>
<param-value>/public/*,*.js,*.css,/druid*,*.jsp,*.swf</param-value>
</init-param>
<init-param>
<param-name>principalSessionName</param-name>
<param-value>sessionInfo</param-value>
</init-param>
<init-param>
<param-name>profileEnable</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>druidWebStatFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2.5:使用Druid数据源-利用ServletRegistrationBean配置druid的web监控和拦截器
在导入数据源的基础上:
package com.wkl.springboot.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.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Description:定制化配置druid数据源
* Date: 2020/6/3 - 下午 12:01
* author: wangkanglu
* version: V1.0
*/
@Configuration
public class DruidConfig {
// 这个注解表示从配置文件中读取这些配置信息
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
//创建servlet注册实体,StatViewServlet是druid的servlet
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,String> initParams = new HashMap<>();
//设置控制台管理用户
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
设置ip白名单
initParams.put("allow","");//默认就是允许所有访问
//设置ip黑名单,如果allow与deny共同存在时,deny优先于allow
initParams.put("deny","");
bean.setInitParameters(initParams);
return bean;
}
//2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
//创建过滤器
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
//忽略过滤的形式
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
//设置过滤器过滤路径
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
效果:
访问http://127.0.0.1:8088/druid即可登录
同时也可以监控我们系统内接口等逻辑处理类,执行的sql可以监控各种信息
3:整合MyBatis
3.1:导入mybatis自己的依赖
<!-- 引入mybatis自己的依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
图解:
3.2:使用mybatis的步骤
1:配置数据源属性(见上一章节)
2:数据库创建表
3:创建javabean
3.3:使用注解版mybatis
指定这是操作数据库的mapper
@Mapper
public interface DepartemetMapper {
@Select("select * from department where id = #{id}")
Department getDepartment(Integer id);
//Options标注告诉系统,改id字段为自增的
@Options(useGeneratedKeys = true,keyProperty = "id")
@Insert("insert into department(departmentName) values(#{departmentName})")
int insertDept(Department department);
@Delete("delete from department where id = #{id}")
int deletDept(Integer id);
@Update("update department set departmentName = #{departmentName} where id = #{id}")
int updateDept(Department department);
}
创建接口访问的Controller
@RestController
public class DepartmentController {
@Autowired
DepartemetMapper departemetMapper;
@GetMapping("/dept/{id}")
public Department getDept(@PathVariable("id") Integer id){
return departemetMapper.getDepartment(id);
}
@GetMapping("/dept")
public Department insertDept(Department department){
departemetMapper.insertDept(department);
return department;
}
}
开启驼峰命名法
#开启mybatis的驼峰命名法
mybatis:
configuration:
map-underscore-to-camel-case: true
使用MapperScan批量扫描所有的Mapper接口;这样就可以不用每个mapper类的都写@Mapper注解
@MapperScan(value = "com.atguigu.springboot.mapper")
@SpringBootApplication
public class SpringBoot06DataMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBoot06DataMybatisApplication.class, args);
}
}
3.4:使用配置版mybatis
指定数据库访问mapper
@Mapper
public interface EmpployeeMapper {
Empployee getEmp(int id);
void insertEmp(Empployee empployee);
}
编写mapper的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.wkl.springboot.mapper.EmpployeeMapper">
<!-- Empployee getEmp(int id);
void insertEmp(Empployee empployee);-->
<select id="getEmp" resultType="com.wkl.springboot.bean.Empployee">
select * from employee where id = #{id}
</select>
<insert id="insertEmp" >
insert into employee(lastName,email,gender,d_id) value (#{lastName},#{email},#{gender},#{dId})
</insert>
</mapper>
编写mybatis的配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 解决关于mybatis的驼峰问题-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
在配置文件中配置上述的配置文件位置
mybatis:
# configuration:
# map-underscore-to-camel-case: true
config-location: classpath:mybatis/mybatis_config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
编写Controller
@RestController
public class EmpController {
@Autowired
EmpployeeMapper empployeeMapper;
@GetMapping("/emp/{id}")
public Empployee getDept(@PathVariable("id") Integer id){
return empployeeMapper.getEmp(id);
}
}
4:整合SpringData jpa
4.1、SpringData简介
4.2:springboot使用SpringData JPA的流程
JPA:ORM(Object Relational Mapping);
1:引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2:编写一个实体类(bean)和数据表进行映射,并且配置好映射关系;
package com.wkl.springboot;
import javax.persistence.*;
/**
* Description:
* Date: 2020/6/7 - 上午 1:34
* author: wangkanglu
* version: V1.0
*/
//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name="tab_user") //@Table来指定和哪个数据表对应;如果省略默认表名就是类名小写user
public class entity {
@Id //这是一个主键
@GeneratedValue(strategy = GenerationType.IDENTITY) //自增主键
private Integer id;
@Column(name = "last_name",length = 50) //这是和数据表对应的一个列
private String lastName;
@Column //省略默认列名就是属性名
private String email;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
3:编写一个Dao接口来操作实体类对应的数据表(Repository)
package com.wkl.springboot.repository;
import com.wkl.springboot.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Description:
* Date: 2020/6/7 - 上午 1:46
* author: wangkanglu
* version: V1.0
*/
//继承JpaRepository来完成对数据库的操作
// 表的类,主键类型
public interface UserReopsitory extends JpaRepository<User, Integer> {
}
4:配置文件中基本的配置JpaProperties
5:创建Controller
package com.wkl.springboot.controller;
import com.wkl.springboot.entity.User;
import com.wkl.springboot.repository.UserReopsitory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* Description:
* Date: 2020/6/7 - 上午 1:51
* author: wangkanglu
* version: V1.0
*/
@RestController
public class UserController {
@Autowired
UserReopsitory userReopsitory;
@GetMapping("/user/{id}")
public User getUser(@PathVariable("id")Integer id){
return userReopsitory.getOne(id);
}
@GetMapping("/user")
public User insertUser(User user){
User save = userReopsitory.save(user);
return save;
}
}
6:使用getUser方法报500错误
错误原因是:在转化成json的时候,fasterxml.jackson将对象转换为json报错,发现有字段为null。
解决方案:实体类上添加
@JsonIgnoreProperties(value = { "hibernateLazyInitializer"})