SpringData简介
对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系型数据库),Spring Boot 底层都是采用 Spring Data 的方式进行统一处理。
Spring Boot 底层都是采用 Spring Data 的方式进行统一处理各种数据库,Spring Data 也是 Spring 中与 Spring Boot、Spring Cloud 等齐名的知名项目。
Sping Data 官网:https://spring.io/projects/spring-data
整合JDBC
创建测试项目测试数据源
1、我去新建一个项目测试:springboot-data-jdbc ; 引入相应的模块!
JDBC API MySQL Driver Spring Web
2、编写application.yaml配置文件连接数据库
spring:datasource:username: rootpassword: shuai# 假如时区报错了,就增加一个时区的配置就ok了 serverTimezone=UTCurl: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.cj.jdbc.Driver
3、配置完这一些东西后,我们就可以直接去使用了,因为SpringBoot已经默认帮我们进行了自动配置;去测试类测试一下
@SpringBootTestclass Springboot04DataApplicationTests {//DI注入数据源@AutowiredDataSource dataSource;@Testvoid contextLoads() throws SQLException {// 查看一下默认数据源:class com.zaxxer.hikari.HikariDataSourceSystem.out.println(dataSource.getClass());// 获得数据库连接Connection connection = dataSource.getConnection();System.out.println(connection);// xxxTemplate : Springboot已经配置好模板bean,拿来即用 CRUD// 关闭connection.close();}}
结果:我们可以看到他默认给我们配置的数据源为 : 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.2.5 默认使用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方法:用于执行存储过程、函数相关语句。
测试
@RestControllerpublic class JDBCController {@AutowiredJdbcTemplate jdbcTemplate;// 查询数据库的所有信息// 没有实体类,数据库中的东西,怎么获取? Map@GetMapping("/userlist")public List<Map<String,Object>> userList(){String sql = "select * from user";List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);return list_maps;}@GetMapping("/adduser")public String addUser(){String sql = "insert into user(id,name,pwd) values(6,'小明','123456')";jdbcTemplate.update(sql);return "add-ok";}@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] = "wwwwww";jdbcTemplate.update(sql,objects);return "updateuser-ok";}@GetMapping("/deleteuser/{id}")public String deleteUser(@PathVariable("id") int id){String sql = "delete from user where id=?";jdbcTemplate.update(sql,id);return "deleteuser-ok";}}
集成Druid
Druid简介
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/
配置数据源
1、添加上 Druid 数据源依赖。
<!-- https://mvnrepository.com/artifact/com.alibaba/druid --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.10</version></dependency>
2、切换数据源;之前已经说过 Spring Boot 2.0 以上默认使用 com.zaxxer.hikari.HikariDataSource 数据源,但可以 通过 spring.datasource.type 指定数据源。
spring:datasource:username: rootpassword: 123456url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource # 自定义数据源
3、数据源切换之后,在测试类中注入 DataSource,然后获取到它,输出一看便知是否成功切换;
4、切换成功!既然切换成功,就可以设置数据源连接初始化大小、最大连接数、等待时间、最小连接数 等设置项;可以查看源码
spring:datasource:username: rootpassword: shuai# 假如时区报错了,就增加一个时区的配置就ok了 serverTimezone=UTCurl: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource#Spring Boot 默认是不注入这些属性值的,需要自己绑定#druid 数据源专有配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4jfilters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
5、导入Log4j 的依赖
<!--log4j--><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.12</version></dependency>
6、现在需要程序员自己为 DruidDataSource 绑定全局配置文件中的参数,再添加到容器中,而不再使用 Spring Boot 的自动生成了;我们需要 自己添加 DruidDataSource 组件到容器中,并绑定属性;
@Configurationpublic class DruidConfig {@ConfigurationProperties(prefix = "spring.datasource")@Beanpublic DataSource druidDataSource(){return new DruidDataSource();}// 后台监控@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");// 后台需要有人登录,账号密码配置HashMap<String, String> initParameters = new HashMap<>();// 添加配置initParameters.put("loginUsername","shuai"); // 登录key 是固定的 loginUsername loginPasswordinitParameters.put("loginPassword","shuai");// 允许谁可以访问initParameters.put("allow","");// 禁止谁能访问 initParameters.put("shaoshaui","192.168.1.2"); // 禁止此ip访问bean.setInitParameters(initParameters); // 设置初始化参数return bean;}// filter@Beanpublic FilterRegistrationBean webStatFilter(){FilterRegistrationBean bean = new FilterRegistrationBean();bean.setFilter(new WebStatFilter());// 可以过滤那些请求呢?HashMap<String, String> initParameters = new HashMap<>();// 这些东西不进行统计~initParameters.put("exclusions","*.js,*.css,/druid/*");bean.setInitParameters(initParameters);return bean;}}
整合Mybatis
整合测试
1、导入 MyBatis 所需要的依赖
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</version></dependency>
2、配置数据库连接信息(不变)
spring:datasource:username: rootpassword: shuai# 假如时区报错了,就增加一个时区的配置就ok了 serverTimezone=UTCurl: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSource#Spring Boot 默认是不注入这些属性值的,需要自己绑定#druid 数据源专有配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4jfilters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3、测试数据库是否连接成功!
4、创建实体类,导入 Lombok!
User.java
@Data@AllArgsConstructor@NoArgsConstructorpublic class User {private int id;private String name;private String pwd;}
5、创建mapper目录以及对应的 Mapper 接口
UserMapper.java
// @Mapper : 这个注解表示了这是一个 mybatis 的 mapper 类: Dao@Mapper@Repositorypublic interface UserMapper {List<User> queryUserList();User queryUserById(int id);int addUser(User user);int updateUser(User user);int deleteUser(int id);}
6、对应的Mapper映射文件
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.shuai.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,pwd) values (#{id},#{name},#{pwd});</insert><update id="updateUser" parameterType="User">update user set name =#{name},pwd=#{pwd} where id =#{id};</update><delete id="deleteUser" parameterType="int">delete from user where id=#{id};</delete></mapper>
8、编写部门的 UserController 进行测试!
UserController.java
@RestControllerpublic class UserController {@Autowiredprivate UserMapper userMapper;@GetMapping("/userlist")public List<User> queryUserList(){List<User> users = userMapper.queryUserList();for (User user : users) {System.out.println(user);}return users;}@GetMapping("/queryuser/{id}")public User queryUserById(@PathVariable("id") int id){User users = userMapper.queryUserById(id);System.out.println(users);return users;}@GetMapping("/adduser")public String addUser(){userMapper.addUser(new User(7,"xiao","4486756"));return "ok";}@GetMapping("/updateuser")public String updateUser(){userMapper.updateUser(new User(7,"xiao帅","4486876"));return "ok";}@GetMapping("/deleteuser/{id}")public String deleteUser(@PathVariable("id") int id){userMapper.deleteUser(id);return "ok";}}
整合完毕,弄完收工!!!
