java框架|SpringBoot入门(九)数据访问

目录
第八章 SQL
8.1 数据源的自动配置-HikariDataSource
8.1.1 导入JDBC场景
8.1.2 分析自动配置
8.1.3 修改配置项
8.1.4 测试
8.2 使用Druid数据源
8.2.1 druid官方github地址
8.2.2 自定义方式
8.2.2.1 创建数据源
8.2.2.2 StatViewServlet
8.2.2.3 StatFilter
8.2.3 使用官方starter方式
8.2.3.1 引入druid-starter
8.2.3.2 分析自动配置
8.2.3.3 配置示例
8.3 整合MyBatis操作
8.3.1 配置模式(推荐)
8.3.2 注解模式
8.3.3 混合模式
8.4 整合MyBatis-Plus完成CRUD
8.4.1 什么是MyBatis-Plus
8.4.2 整合MyBatis-Plus
8.4.3 CRUD功能
第九章 NoSQL
9.1 Redis自动配置
9.2 RedisTemplate与Lettuce
9.3 切换至Jedis
第八章 SQL 8.1 数据源的自动配置-HikariDataSource 8.1.1 导入JDBC场景


org.springframework.boot
spring-boot-starter-data-jdbc

java框架|SpringBoot入门(九)数据访问
文章图片

导入场景后,发现官方没有导入数据库驱动,因为官方不知道接下来我们需要操作哪种数据库。数据库驱动需要自己手动导入。
导入MySQL驱动后,官方会自动仲裁版本。但是要注意数据库版本和驱动版本要对应。
8.0.28 mysql mysql-connector-java

想要修改版本的方法:
1.直接依赖引入具体版本(maven的就近依赖原则)
mysql mysql-connector-java 5.1.49

2.重新声明版本(maven的属性的就近优先原则)
1.8 5.1.49

8.1.2 分析自动配置
  • DataSourceAutoConfiguration:数据源的自动配置
    • 修改数据源相关的配置:spring.datasource
    • 数据库连接池的配置,是自己容器中没有DataSource才自动配置的
    • 底层配置好的连接池是:HikariDataSource
java框架|SpringBoot入门(九)数据访问
文章图片

java框架|SpringBoot入门(九)数据访问
文章图片

  • DataSourceTransactionManagerAutoConfiguration:事务管理器的自动配置
  • JdbcTemplateAutoConfiguration:JdbcTemplate的自动配置,可以来对数据库进行crud
    • 可以修改这个配置项@ConfigurationProperties(prefix = "spring.jdbc") 来修改JdbcTemplate
    • @Bean@Primary JdbcTemplate,容器中有这个组件
  • JndiDataSourceAutoConfiguration:jndi的自动配置
  • XADataSourceAutoConfiguration:分布式事务相关的
8.1.3 修改配置项
配置yaml文件:
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_account
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
8.1.4 测试
@Slf4j @SpringBootTest class Boot05WebAdminApplicationTests {@Autowired JdbcTemplate jdbcTemplate; @Test void contextLoads() {//jdbcTemplate.queryForObject("select * from account_tbl") //jdbcTemplate.queryForList("select * from account_tbl",) Long aLong = jdbcTemplate.queryForObject("select count(*) from account_tbl", Long.class); log.info("记录总数:{}",aLong); }}

8.2 使用Druid数据源 8.2.1 druid官方github地址
GitHub - alibaba/druid: 阿里云计算平台DataWorks(https://help.aliyun.com/document_detail/137663.html) 团队出品,为监控而生的数据库连接池
整合第三方技术的两种方式:
1.自定义
2.找场景starter
8.2.2 自定义方式
8.2.2.1 创建数据源
com.alibaba druid 1.1.17


destroy-method="close">














现在定义一个配置类:
public class MyDataSourceConfig { @ConfigurationProperties("spring.datasource") @Bean public DataSource dataSource(){ DruidDataSource druidDataSource = new DruidDataSource(); //所有的属性也可以从配置文件中获取 return druidDataSource; } }

8.2.2.2 StatViewServlet
Druid内置提供了一个StatViewServlet用于展示Druid的统计信息。
这个StatViewServlet的用途包括:
①提供监控信息展示的html页面
②提供监控信息的JSON API
以前是在web.xml文件中注册这个Servlet

DruidStatView
com.alibaba.druid.support.http.StatViewServlet


DruidStatView
/druid/*

现在在配置文件中注册:
/** * 配置druid的监控页功能 * @return */ @Bean public ServletRegistrationBean statViewServlet(){ StatViewServlet statViewServlet = new StatViewServlet(); ServletRegistrationBean servletServletRegistrationBean = new ServletRegistrationBean<>(statViewServlet,"/druid/*"); return servletServletRegistrationBean; }

8.2.2.3 StatFilter
用于统计监控信息;如SQL监控、URI监控
需要给数据源中配置如下属性:可以允许多个filter,多个用,分割,如:

在配置文件中的数据源配置中设置filters属性:
@SneakyThrows @ConfigurationProperties("spring.datasource") @Bean public DataSource dataSource(){ DruidDataSource druidDataSource = new DruidDataSource(); //所有的属性也可以从配置文件中获取 //加入监控功能的属性 druidDataSource.setFilters("stat,wall"); //wall是防火墙监控 return druidDataSource; }

系统中所有filter:
别名 Filter类名
default
com.alibaba.druid.filter.stat.StatFilter
stat
com.alibaba.druid.filter.stat.StatFilter
mergeStat
com.alibaba.druid.filter.stat.MergeStatFilter
encoding
com.alibaba.druid.filter.encoding.EncodingConvertFilter
log4j
com.alibaba.druid.filter.logging.Log4jFilter
log4j2
com.alibaba.druid.filter.logging.Log4j2Filter
slf4j
com.alibaba.druid.filter.logging.Slf4jLogFilter
commonlogging
com.alibaba.druid.filter.logging.CommonsLogFilter
8.2.3 使用官方starter方式
上面自定义的方法比较复杂繁琐,现在可以利用SpringBoot的场景自动配置。
8.2.3.1 引入druid-starter

com.alibaba
druid-spring-boot-starter
1.1.17

8.2.3.2 分析自动配置
java框架|SpringBoot入门(九)数据访问
文章图片

  • 扩展配置项spring.datasource.druid
  • DruidSpringAopConfiguration.class,监控SpringBean的,配置项:spring.datasource.druid.aop-patterns
  • DruidStatViewServletConfiguration.class,监控页的配置:spring.datasource.druid.stat-view-servlet,默认开启
  • DruidWebStatFilterConfiguration.class,web监控配置:spring.datasource.druid.web-stat-filter,默认开启
  • DruidFilterConfiguration.class,所有Druid自己filter的配置,就是上面自定义的stat、wall等等
private static final String FILTER_STAT_PREFIX = "spring.datasource.druid.filter.stat"; private static final String FILTER_CONFIG_PREFIX = "spring.datasource.druid.filter.config"; private static final String FILTER_ENCODING_PREFIX = "spring.datasource.druid.filter.encoding"; private static final String FILTER_SLF4J_PREFIX = "spring.datasource.druid.filter.slf4j"; private static final String FILTER_LOG4J_PREFIX = "spring.datasource.druid.filter.log4j"; private static final String FILTER_LOG4J2_PREFIX = "spring.datasource.druid.filter.log4j2"; private static final String FILTER_COMMONS_LOG_PREFIX = "spring.datasource.druid.filter.commons-log"; private static final String FILTER_WALL_PREFIX = "spring.datasource.druid.filter.wall";

8.2.3.3 配置示例
在yaml文件中进行配置:
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_account
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
druid:
aop-patterns: com.xxy.springbootproject.*#监控SpringBean
filters: stat,wall# 底层开启功能,stat(sql监控),wall(防火墙)
stat-view-servlet:# 配置监控页功能
enabled: true
login-username: admin
login-password: 123456
resetEnable: false
web-stat-filter:# 监控web
enabled: true
urlPattern: /*
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'

filter:
stat:# 对上面filters里面的stat的详细配置
slow-sql-millis: 1000
logSlowSql: true
enabled: true
wall:
enabled: true
config:
drop-table-allow: false
8.3 整合MyBatis操作 https://github.com/mybatis
SpringBoot官方的starter:spring-boot-starter-*
第三方的starter: *-spring-boot-starter
org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.4

java框架|SpringBoot入门(九)数据访问
文章图片

8.3.1 配置模式(推荐)
  • 全局配置文件
  • mybatis会自动连接上配置好的datasource
  • SqlSessionFactory:自动配置好了
  • SqlSession:自动配置了SqlSessionTemplate,组合了SqlSession
  • @Import(AutoConfiguredMapperScannerRegistrar.class)
  • Mapper:只要我们写的操作MyBatis的接口标注了@Mapper就会被自动扫描进来
java框架|SpringBoot入门(九)数据访问
文章图片

java框架|SpringBoot入门(九)数据访问
文章图片

可以修改配置文件中mybatis开头的所有属性:
# 配置mybatis规则
mybatis:
#config-location: classpath:mybatis/mybatis-config.xml
mapper-locations: classpath:mybatis/mapper/*.xml
configuration: #指定mybatis全局配置文件中的相关配置项
map-underscore-to-camel-case: true #开启驼峰命名自动映射

可以不写全局配置文件,所有全局配置文件的配置都放在configuration配置项中即可(推荐)
配置private Configuration configuration; mybatis.configuration下面的所有,就是相当于改mybatis全局配置文件中的值(与使用全局配置文件进行配置不能同时存在)
java框架|SpringBoot入门(九)数据访问
文章图片

全局配置文件的模板:

mapper映射文件模板:
select * from Blog where id = #{id}

步骤:
  • 导入mybatis官方starter
  • 编写mapper接口,标注@Mapper注解
  • 编写sql映射文件并绑定mapper接口
  • 在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息(建议:配置在mybatis.configuration)
8.3.2 注解模式
@Mapper public interface CityMapper {@Select("select * from city where id=#{id}") public City getById(Long id); }

8.3.3 混合模式
简单的语句可以使用注解模式,复杂的语句可以使用mapper映射文件配置模式。
@Mapper public interface CityMapper {@Select("select * from city where id=#{id}") public City getById(Long id); public void insert(City city); }

java框架|SpringBoot入门(九)数据访问
文章图片

java框架|SpringBoot入门(九)数据访问
文章图片

最佳步骤:
  • 引入mybatis-starter
  • 配置application.yaml中,指定mapper-location位置即可
  • 编写Mapper接口并标注@Mapper注解
  • 简单方法直接注解方式
  • 复杂方法编写mapper.xml进行绑定映射
  • 在主配置类上加上注解@MapperScan,就不需要再每一个Mapper接口上加@Mapper注解;了,如@MapperScan("com.xxy.springbootproject.mapper")
8.4 整合MyBatis-Plus完成CRUD 8.4.1 什么是MyBatis-Plus
MyBatis-Plus(简称MP)是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。
【java框架|SpringBoot入门(九)数据访问】MyBatis-Plus
建议安装MybatisX插件。
8.4.2 整合MyBatis-Plus

com.baomidou
mybatis-plus-boot-starter
3.4.1

java框架|SpringBoot入门(九)数据访问
文章图片

此时可以不再引入jdbc、mybatis的依赖。
自动配置:
java框架|SpringBoot入门(九)数据访问
文章图片

java框架|SpringBoot入门(九)数据访问
文章图片

java框架|SpringBoot入门(九)数据访问
文章图片

  • MybatisPlusAutoConfiguration配置类,MybatisPlusProperties配置项绑定,mybatis-plus:xxx就是对mybatis-plus的定制
  • SqlSessionFactory自动配置好,底层是容器中默认的数据源
  • mapperLocations自动配置好的,有默认值。
    • classpath*:/mapper/**/*.xml:任意包的类路径下的所有mapper文件夹下任意路径下的所有xml都是sql映射文件,建议以后sql映射文件,放在mapper下
  • 容器中也自动配置好了SqlSessionTemplate
  • @Mapper 标注的接口也会被自动扫描。建议直接 @MapperScan("com.xxy.springbootproject.mapper") 批量扫描就行
优点:
只需要我们的Mapper继承BaseMapper就可以拥有crud能力,只有当这个类内的方法不能用
时,可以自己写一个xml映射文件。
java框架|SpringBoot入门(九)数据访问
文章图片

java框架|SpringBoot入门(九)数据访问
文章图片

8.4.3 CRUD功能
默认情况下认为数据库内的表名就是user,默认会去查找user表,如果表名不叫user,那么就使用注解@TableName来指定表名。
实体类:
@Data //@TableName("user_tbl") //指定数据库中实际表名 public class User { private Long id; private String name; private Integer age; private String email; }

Mapper类:
public interface UserMapper extends BaseMapper {}

测试类:
@SpringBootTest public class SampleTest {@Autowired private UserMapper userMapper; @Test public void testSelect() { User user = userMapper.selectById(1L); log.info("用户信息:{}",user); }}

一个创建业务层的例子:使用MyBatis-Plus也可以简化Service层的开发。IService是一个顶级Service
@Service public class UserServiceImpl extends ServiceImpl implements UserService {}public interface UserService extends IService {}

第九章 NoSQL Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。 它支持多种类型的数据结构,如 字符串(strings), 散列(hashes), 列表(lists), 集合(sets), 有序集合(sorted sets) 与范围查询, bitmaps, hyperloglogs 和 地理空间(geospatial) 索引半径查询。 Redis 内置了 复制(replication),LUA脚本(Lua scripting), LRU驱动事件(LRU eviction),事务(transactions) 和不同级别的 磁盘持久化(persistence), 并通过 Redis哨兵(Sentinel)和自动 分区(Cluster)提供高可用性(high availability)
9.1 Redis自动配置

org.springframework.boot
spring-boot-starter-data-redis

java框架|SpringBoot入门(九)数据访问
文章图片

自动配置:
  • RedisAutoConfiguration自动配置类,RedisProperties属性类--->spring.redis.xxx是对redis的配置
java框架|SpringBoot入门(九)数据访问
文章图片

java框架|SpringBoot入门(九)数据访问
文章图片

  • 连接工厂RedisConnectionFactory是准备好的,LettuceConnectionConfiguration、JedisConnectionConfiguration
  • 自动注入了RedisTemplate,key:value是Object
  • 自动注入了StringRedisTemplate,key:value都是String
java框架|SpringBoot入门(九)数据访问
文章图片

  • key:value
  • 底层只要我们使用StringRedisTemplate、RedisTemplate就可以操作redis
9.2 RedisTemplate与Lettuce
spring:
redis:
host: redis所在主机地址
port: 6379端口号
password: 密码组成是账号:密码
@Slf4j @SpringBootTest class SpringbootProjectApplicationTests { @Autowired StringRedisTemplate stringRedisTemplate; @Autowired RedisTemplate redisTemplate; @Test void testRedis(){ ValueOperations operations = redisTemplate.opsForValue(); operations.set("hello","world"); String hello = operations.get("hello"); System.out.println(hello); }}

RedisTemplate底层使用的连接是Lettuce。
9.3 切换至Jedis


redis.clients
jedis

spring:
redis:
host: redis所在主机地址
port: 6379端口号
password: 密码组成是账号:密码
client-type: jedis
jedis:
pool:
max-active: 10 #调节连接池大小

PS:根据尚硅谷课程整理,如有侵权,联系删除。

    推荐阅读