文章目录
Spring Data
简介
对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系型数据库),Spring Boot 底层都是采用 Spring Data 的方式进行统一处理。
Spring Boot 底层都是采用 Spring Data 的方式进行统一处理各种数据库,Spring Data 也是 Spring 中与 Spring Boot、Spring Cloud 等齐名的知名项目。
springboot整合JDBC
创建测试项目测试数据源
1、新建一个项目测试:springboot-data-jdbc ; 引入相应的模块!基础模块
spring web JDBC API MySQL Driver
2、查看pom.xml文件,查看启动器是否导入
<!--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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
3、编写yaml配置文件连接数据库;
spring:
datasource:
username: root
password: 123456
#假如时区报错了,就增加一个时区配置:serverTimezone=UTC
url: jdbc:mysql://localhost:3306/mybatisdb?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
4、配置完这些东西后,我们就可以直接去使用了,因为SpringBoot已经默认帮我们进行了自动配置;去测试类测试一下
@SpringBootTest
class Springboot04DataApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看默认的数据源:com.zaxxer.hikari.HikariDataSource
System.out.println(dataSource.getClass());
//获得数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
//xxx Template : spring boot已经配置好模版bean,获取到即用 CRUD
//关闭
connection.close();
}
}
结果:我们可以看到他默认给我们配置的数据源为 :class com.zaxxer.hikari.HikariDataSource
, 我们并没有手动配置
我们来全局搜索一下,找到数据源的所有自动配置都在 :DataSourceAutoConfiguration
文件:
@Import(
{Hikari.class, Tomcat.class, Dbcp2.class, Generic.class, DataSourceJmxConfiguration.class}
)
protected static class PooledDataSourceConfiguration {
protected PooledDataSourceConfiguration() {
}
}
这里导入的类都在 DataSourceConfiguration
配置类下,可以看出 Spring Boot 2.5.4 默认使用HikariDataSource
数据源,而以前版本,如 Spring Boot 1.5 默认使用org.apache.tomcat.jdbc.pool.DataSource
作为数据源;
HikariDataSource
号称 Java WEB 当前速度最快的数据源,相比于传统的 C3P0
、DBCP
、Tomcat jdbc
等连接池更加优秀;
可以使用 spring.datasource.type
指定自定义的数据源类型,值为 要使用的连接池实现的完全限定名
。
JDBCTemplate
1、有了数据源(com.zaxxer.hikari.HikariDataSource
),然后可以拿到数据库连接(java.sql.Connection
),有了连接,就可以使用原生的 JDBC 语句来操作数据库;
2、即使不使用第三方第数据库操作框架,如 MyBatis等,Spring 本身也对原生的JDBC 做了轻量级的封装,即JdbcTemplate
。
3、数据库操作的所有 CRUD 方法都在 JdbcTemplate
中。
4、Spring Boot 不仅提供了默认的数据源,同时默认已经配置好了 JdbcTemplate
放在了容器中,程序员只需自己注入即可使用
5、JdbcTemplate
的自动配置是依赖 org.springframework.boot.autoconfigure.jdbc
包下的 JdbcTemplateConfiguration
类
JdbcTemplate主要提供以下几类方法:
- execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
- update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;
- query方法及queryForXXX方法:用于执行查询相关语句;
- call方法:用于执行存储过程、函数相关语句。
测试
package com.zhu.controller;
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.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.jws.Oneway;
import java.util.List;
import java.util.Map;
@RestController
public class JDBCController {
/**
* Spring Boot 默认提供了数据源,默认提供了 org.springframework.jdbc.core.JdbcTemplate
* JdbcTemplate 中会自己注入数据源,用于简化 JDBC操作
* 还能避免一些常见的错误,使用起来也不用再自己来关闭数据库连接
*/
@Autowired
JdbcTemplate jdbcTemplate;
//查询数据库的所有信息
//没有实体类,数据库中的东西,怎么获取? Map
//List 中的1个 Map 对应数据库的 1行数据
//Map 中的 key 对应数据库的字段名,value 对应数据库的字段值
@GetMapping("/userList")
public List<Map<String,Object>> userList(){
String sql="select * from user";
List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
return mapList;
}
@GetMapping("/addUser")
public String addUser(){
String sql = "insert into mybatisdb.user (name,addr,age) values('小米','北京',18)";
jdbcTemplate.update(sql);
return "update-ok";
}
@GetMapping("updateUser/{id}")
public String updateUser(@PathVariable("id") Integer id){
String sql = "update mybatisdb.user set name=?,addr=?,age=? where id="+id;
//封装
Object[] objects = new Object[3];
objects[0]="小孩";
objects[1]="天津";
objects[2]=12;
jdbcTemplate.update(sql,objects);
return "updateUser-ok";
}
@GetMapping("/deleteUser/{id}")
public String deleteUser(@PathVariable("id") Integer id){
String sql = "delete from mybatisdb.user where id=?";
jdbcTemplate.update(sql,id);
return "deleteUser-ok";
}
}
整合Druid
Druid简介
Apache Druid是一个高性能的实时分析型数据库
- 云原生、流原生的分析型数据库
- 可轻松与现有的数据管道进行集成
- 较传统方案提升近百倍的效率
- 解锁了一种新型的工作流程
- 可部署在AWS/GCP/Azure,混合云,Kubernetes, 以及裸机上
Java程序很大一部分要操作数据库,为了提高性能操作数据库的时候,又不得不使用数据库连接池。
Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0
、DBCP
等 DB
池的优点,同时加入了日志监控
Druid 可以很好的监控 DB 池连接
和 SQL 的执行情况
,天生就是针对监控而生的DB 连接池
。
Druid
已经在阿里巴巴部署了超过600
个应用,经过一年多生产环境大规模部署的严苛考验。
Spring Boot 2.0
以上默认使用 Hikari
数据源,可以说 Hikari
与 Driud
都是当前 Java Web
上最优秀的数据源,我们来重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控。
Github地址:https://github.com/alibaba/druid/
com.alibaba.druid.pool.DruidDataSource
基本配置参数如下:
配置数据源
配置数据源
1、添加上 Druid
数据源依赖与导入Log4j
的依赖。
<!-- Druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2、修改yml
文件,切换数据源
;之前已经说过 Spring Boot 2.0 以上默认使用 com.zaxxer.hikari.HikariDataSource
数据源,但可以 通过 spring.datasource.type
指定数据源。
spring:
datasource:
username: root
password: 123456
#假如时区报错了,就增加一个时区配置:serverTimezone=UTC
url: jdbc:mysql://localhost:3306/mybatisdb?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
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注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3、为 DruidDataSource
绑定全局配置文件中的参数,再添加到容器中,而不再使用 Spring Boot 的自动生成了;我们需要 自己添加 DruidDataSource
组件到容器中,并绑定属性;
import javax.sql.DataSource;
@Configuration
public class DruidConfig {
/*
将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
@ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
*/
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
}
4、去测试类中测试一下;看是否成功!
@SpringBootTest
class SpringbootDataJdbcApplicationTests {
//DI注入数据源
@Autowired
DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
//看一下默认数据源
System.out.println(dataSource.getClass());
//获得连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
DruidDataSource druidDataSource = (DruidDataSource) dataSource;
System.out.println("druidDataSource 数据源最大连接数:" + druidDataSource.getMaxActive());
System.out.println("druidDataSource 数据源初始化连接数:" + druidDataSource.getInitialSize());
//关闭连接
connection.close();
}
}
输出结果 :可见配置参数就说明已经生效!
配置Druid数据源监控
配置Druid数据源监控
@Configuration
public class DruidConfig {
/*
将自定义的 Druid数据源添加到容器中,不再让 Spring Boot 自动创建
绑定全局配置文件中的 druid 数据源属性到 com.alibaba.druid.pool.DruidDataSource从而让它们生效
@ConfigurationProperties(prefix = "spring.datasource"):作用就是将 全局配置文件中
前缀为 spring.datasource的属性值注入到 com.alibaba.druid.pool.DruidDataSource 的同名参数中
*/
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
//后台监控:web.xml ServletRegistrationBean
//因为SpringBoot 内置了 servlet 容器,所以没有web.xml 替代方法:ServletRegistrationBean
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// 这些参数可以在 com.alibaba.druid.support.http.StatViewServlet的父类 com.alibaba.druid.support.http.ResourceServlet 中找到
//后台需要有人登陆,账号密码配置
Map<String,String> initParameters = new HashMap<>();
//增加配置
initParameters.put("loginUsername", "admin");//登录key 是固定的 loginUsername loginPassword
initParameters.put("loginPassword", "123456");
//允许谁可以访问
//initParams.put("allow", "localhost"):表示只有本机可以访问
initParameters.put("allow", "");//为空或者为null时,表示允许所有访问
//deny:Druid 后台拒绝谁访问
//禁止谁能访问 initParameters.put("zhangsan","192.168.20.123")
bean.setInitParameters(initParameters);//设置初始化参数
return bean;
}
}
配置完毕后,我们可以选择访问 :http://localhost:8080/druid
配置 Druid web 监控 filter 过滤器
//配置 Druid 监控 之 web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//可以过滤哪些请求呢?
Map<String,String> initParameters = new HashMap<>();
//这些东西不进行统计
//exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
initParameters.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParameters);//设置初始化参数
//"/*" 表示过滤所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
整合mybatis
官方文档:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
Maven仓库地址:https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter/2.1.1
整合包:mybatis-spring-boot-starter
- 导入依赖
<!-- mybatis-spring-boot-stater:整合-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
- 配置文件
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/mybatisdb?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- mybatis配置
#整合mybatis
mybatis.type-aliases-package=com.zhu.pojo
mybatis.mapper-locations=classpath:mapper/*.xml
- 编写SQL
<?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.zhu.mapper.UserMapper">
<select id="queryUserList" resultType="User">
select * from user;
</select>
<select id="queryUserById" resultType="User">
select * from user where id=#{id};
</select>
<insert id="addUser" parameterType="User">
insert into user (id,name,addr,age) values (#{id},#{name},#{addr},#{age})
</insert>
<update id="updateUser" parameterType="User">
update user set name=#{name},addr=#{addr},age=#{age} where id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete>
</mapper>
- service层调用dao层
- controller调用service层
package com.zhu.controller;
import com.zhu.mapper.UserMapper;
import com.zhu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("queryUserList")
public List<User> queryUserList(){
List<User> userList = userMapper.queryUserList();
for (User user : userList) {
System.out.println(user);
}
return userList;
}
@GetMapping("addUser")
public String addUser(){
userMapper.addUser(new User(19,"红红","湖南",23));
return "add ok";
}
@GetMapping("deleteUser")
public String deleteUser(){
userMapper.deleteUser(1);
return "deleteUser ok";
}
@GetMapping("updateUser")
public String updateUser(){
userMapper.updateUser(new User(1,"Joker","九航",18));
return "updateUser ok";
}
}
编写Mapper接口
package com.zhu.mapper;
import com.zhu.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
//这个注解表示了这是一个 mybatis 的 mapper类
@Mapper
@Repository
public interface UserMapper {
List<User> queryUserList();
User queryUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}