文章目录
一、整合jdbc
我们前期已经实现了springboot中的mvc阶段,现在我们开始着手于Data阶段。首先我们先来整合jdbc
第一步:添加相关依赖
在创建项目时,添加相关依赖(jdbc、driver)。当然你也可以不在项目创建是添加依赖,而是在项目创建完成后,手动的在pom.xml中添加依赖。
第二步:测试数据源与数据库连接(可略)
测试数据源与数据库连接。我们可以发现springboot默认使用的是hikari数据源
,使用的是原生的jdbc连接。
hikari数据源数据源号称是世界上最快的数据源,很优秀。
package com.tiger;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class SpringbootDataApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看默认的数据源
System.out.println(dataSource.getClass());
//获得数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
第三步:配置数据库连接
在application.yaml中配置数据库连接。无论你是否使用空间,在连接jdbc时都会使用到四个条件:username、password、url、driver。
spring:
datasource:
username: root
password: root123123
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
第四步:使用JdbcTemplate模版
使用JdbcTemplate模版。JdbcTemplate 中封装了大量的实用方法,比如:queryForList(String sql)将查询到的结果封装成List直接返回。
springboot给我们提供了响应的模版(JdbcTemplate),了解过spring的朋友可以知道,在spring中有一个SqlSessionTemplate,在这里springboot给我们提供了现成的模版,我们可以直接使用。在springboot中我们后期会了解更多的模版,只要是XxxTemplate我们都可以拿来即用,非常的方便。
package com.tiger.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class JDBCContorller {
@Autowired
JdbcTemplate jdbcTemplate;
@RequestMapping("/getAllInfo")
public List<Map<String, Object>> getAllInfo(){
String sql = "select * from user";
List<Map<String, Object>> lists = jdbcTemplate.queryForList(sql);
return lists;
}
}
测试:
二、整合Druid
说是整合Druid,不如说是在整合JDBC阶段是替换数据源。当我们使用druid替换hikari之后,相关的SQL操作代码不会发生任何的改变
,我们只是替换了数据源。
Druid简介
Druid首先是一个数据库连接池。Druid是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。
Druid的功能
-
替换DBCP和C3P0
。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。 -
可以
监控数据库访问性能
,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能
。 -
数据库密码加密
。直接把数据库密码写在配置文件中,这是不好的行为,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。 -
SQL执行日志
,Druid提供了不同的LogFilter,能够支持Common-Logging、Log4j(下面我们会以Log4j为例)和JdkLog
,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。 -
扩展JDBC
,如果你要对JDBC层有编程的需求,可以通过Druid提供的Filter机制,很方便编写JDBC层的扩展插件。
综上所述,Druid充当数据库连接池、可以监控数据库访问性能、可以获得SQL执行日志。
在springboot中使用Druid
第一步:添加相关依赖
因为druid提供了SQL执行日志的功能,而我们的QL执行日志是依赖于Log4j
的,所以我们既需要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>
第二步:切换数据源
在整合JDBC时,我们可以清楚的看到,springboot默认使用的是hikari数据源,我们需要将其切换成druid的数据源。
spring:
datasource:
username: root
password: root123123
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource #切换数据源
测试数据源
package com.tiger;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
@SpringBootTest
class SpringbootDataApplicationTests {
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看默认的数据源
System.out.println(dataSource.getClass());
//获得数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
我们可以发现经过type: com.alibaba.druid.pool.DruidDataSource
的操作后,数据源变成了DruidDataSource
。
第三步:配置Druid参数
druid与Hikari的区别在于,druid除了具有一些常规的连接池的功能外,还具有监控统计拦截和SQL日志的功能。
下面的application.yaml
中的是可以满足绝大多数需求的druid的相关配置。
spring:
datasource:
username: root
password: password
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
initialSize: 5
minIdle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的 Filter,去掉后监控界面 SQL 无法统计,wall 用于防火墙 日志 log4j
filters: stat,wall,log4j #导入了log4j
useGlobalDataSourceStat: true
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
Druid的监控统计拦截和SQL日志的功能,是需要我们手动进行配置的,如下:其中的map中的键值你可以通过点击StatViewServlet-->ResourceServlet
和WebStatFilter
进行查看。
package com.tiger.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.servlet.Filter;
import javax.sql.DataSource;
import java.util.HashMap;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
//后台监控功能
//因为springboot内置了servlet容器,所以没有web.xml。替代方法 ServletRegistrationBean
@Bean
public ServletRegistrationBean StatViewServlet(){
//固定写法
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>();
bean.setServlet(new StatViewServlet());
bean.addUrlMappings("/druid/*"); //"/druid/*"不是固定的你也可以写成"/tiger/*"
//后台需要有人登陆
HashMap<String , String> initParameters = new HashMap<>();
//增加配置
initParameters.put("loginUsername","admin");//"loginUsername"是固定的
initParameters.put("loginPassword","123456"); //"loginPassword"是固定的
//允许谁能访问
initParameters.put("allow",""); //("allow","localhost")只允许本机访问;("allow","")允许所有人访问;
//禁止谁访问 initParameters.put("tiger","192.168.0.1");
//设置初始化参数
bean.setInitParameters(initParameters);
return bean;
}
//Filter
@Bean
public FilterRegistrationBean b(){
//固定写法
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
bean.setFilter(new WebStatFilter());
//可以过滤那些请求
HashMap<String , String > initParameters = new HashMap<>();
initParameters.put("exclusions","*.js,*.css,/druid/*");
//设置初始化参数
bean.setInitParameters(initParameters);
return bean;
}
}
访问:http://localhost:8080/druid/
三、整合mybatis
如果你是用过SSM框架,你应该会觉得在整合spring和mybatis的啥时候,那些配置文件真的是让人头大。但是在springboot中,一切都变的那么简单。
第一步:添加相关依赖
在创建项目时,添加相关依赖(jdbc、driver)。当然你也可以不在项目创建是添加依赖,而是在项目创建完成后,手动的在pom.xml中添加依赖。
jdbc依赖和driver依赖
第三方提供的整合包依赖
之所以在springboot中整合mybatis变得很简单,这个整合包依赖起到很大的作用。
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
第二步:配置数据库连接
不多说了,这个是必备的。(application.yaml
)
spring:
datasource:
username: root
password: password
url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
第三步:给实体类起别名
在mybatis中我们是在mybatis-config.xml进行配置别名的,但是在springboot中我们是在application.yaml
中进行配置的,如下:
mybatis:
type-aliases-package: com.tiger.pojo # 别名包
在 com.tiger.pojo
下的实体类都将一类名作为别名。
第四步:配置mapper映射
在mybatis中我们是在mybatis-config.xml进行配置mapper映射的,但是在springboot中我们是在application.yaml
中进行配置的,如下:
mybatis:
mapper-locations: classpath:mybatis/mapper/*.xml #mapper的位置
classpath:mybatis/mapper/*.xml定位到的位置是,如下:
第五步:测试
①、编写实体类
编写实体类我们使用lombok
,lombok的依赖如下:
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
实体类(src\main\java\com\tiger\pojo\User.java)
package com.tiger.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String passwd;
}
②、编写XxxMapper.xml
位置:resources/mybatis/mapper/UserMapper.xml
你也可以使用注解实现增、删、改、查(CRUD)【点击查看】
<?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-->
<mapper namespace="com.tiger.mapper.UserMapper">
<select id="getAllInfo" resultType="User" >
select * from `user`
</select>
</mapper>
③、编写测试Controller
package com.tiger.controller;
import com.tiger.mapper.UserMapper;
import com.tiger.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/getAllInfo")
public List<User> getAllInfo(){
List<User> allInfo = userMapper.getAllInfo();
return allInfo;
}
}
访问:http://localhost:8080/getAllInfo
只要朝着一个方向努力,一切都会变得得心应手…