SpringBoot笔记(6)
一、数据访问(SQL)
1、数据源的自动配置-HikariDataSource
1、导入JDBC场景
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
数据库版本和驱动版本对应
默认版本:<mysql.version>8.0.22</mysql.version>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!-- <version>5.1.49</version>-->
</dependency>
想要修改版本
1、直接依赖引入具体版本(maven的就近依赖原则)
2、重新声明版本(maven的属性的就近优先原则)
<properties>
<java.version>1.8</java.version>
<mysql.version>5.1.49</mysql.version>
</properties>
2、分析自动配置
1、自动配置的类
DataSourceAutoConfiguration : 数据源的自动配置
- 修改数据源相关的配置:spring.datasource
- 数据库连接池的配置,是自己容器中没有DataSource才自动配置的
- 底层配置好的连接池是:HikariDataSource
DataSourceTransactionManagerAutoConfiguration: 事务管理器的自动配置
JdbcTemplateAutoConfiguration: JdbcTemplate的自动配置,可以来对数据库进行crud
- 可以修改这个配置项@ConfigurationProperties(prefix = "spring.jdbc") 来修改JdbcTemplate
- @Bean@Primary JdbcTemplate;容器中有这个组件
JndiDataSourceAutoConfiguration: jndi的自动配置
XADataSourceAutoConfiguration: 分布式事务相关的
3、修改配置项
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_account
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
4、测试
@Slf4j
@SpringBootTest
class Boot01WebAdminApplicationTests {
//自动注入jdbcTemplate
@Autowired
JdbcTemplate jdbcTemplate;
@Test
void contextLoads() {
Long aLong = jdbcTemplate.queryForObject("select count(*) from item", Long.class);
log.info("查询数量为:{}",aLong);
}
}
2、使用Druid数据源
1、druid官方github地址
https://github.com/alibaba/druid
整合第三方技术的两种方式
- 自定义
- 找starter
2、自定义方式
3、使用官方stater方式
1、引入druid-starter
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
2、分析自动配置
扩展配置项 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的配置
3、配置示例
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_account
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
druid:
aop-patterns: com.atguigu.admin.* #监控SpringBean
filters: stat,wall # 底层开启功能,stat(sql监控),wall(防火墙)
stat-view-servlet: # 配置监控页功能
enabled: true
login-username: admin
login-password: admin
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
SpringBoot配置示例
https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
4、监控页
http://localhost:8080/druid/进入数据源的监控页
3、整合Mybatis操作
0、导入mybatis的依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
1、编写Mapper接口(添加@mapper注解)
package gyb.boot01webadmin.mapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ItemMapper {
/**
* 查询item的数量
* @return
*/
Long SumItemNum();
}
1、编写mabatis全局配置文件
<?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> </configuration>
2、编写映射文件
<?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="gyb.boot01webadmin.mapper.ItemMapper"> <select id="SumItemNum" resultType="Long"> select count(*) from item </select></mapper>
3、编写yaml中的mybatis相关配置
mybatis: # config-location: classpath:mybatis/mybatis-config.xml mapper-locations: classpath:mybatis/mapper/*.xml configuration: #开启驼峰命名法 map-underscore-to-camel-case: true
4、测试
@AutowiredItemService itemService;@GetMapping("/db")@ResponseBodypublic String dbTest(){ Long num = itemService.SumItemNum(); return num.toString();}
5、注解模式
@Mapperpublic interface CityMapper { @Select("select * from city where id=#{id}") @Options(useGeneratedKeys= true, keyProperty=id) public City getById(Long id); public void insert(City city);}
6、tip: 获取自增主键
insert ... .. ... .
4、整合 MyBatis-Plus 完成CRUD
1、什么是MyBatis-Plus
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
建议安装 MybatisX 插件
2、开发步骤
1、导入依赖
导入后不需要导入mybatis-spring的依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version></dependency>
2、配置数据库
spring: datasource: url: jdbc:mysql://localhost:3306/db_account username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver druid: aop-patterns: com.atguigu.admin.* #监控SpringBean filters: stat,wall # 底层开启功能,stat(sql监控),wall(防火墙) stat-view-servlet: # 配置监控页功能 enabled: true login-username: admin login-password: admin 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
3、在在 Spring Boot 启动类中添加 @MapperScan 注解
扫描 Mapper 文件夹:
@MapperScan("gyb.mapper")
4、编写实体类、Mapper接口(继承)
@TableField(exist = false):去除表中不存在的字段
@Data//使用Mybatis时,实体类的属性都应存在于数据库public class User { //注解表示此属性不存在数据库的字段与之对应 @TableField(exist = false) private String username; @TableField(exist = false) private String password; private Long id; private String name; private Integer age; private String email;}
继承BaseMapper<>泛型为要映射的对象
public interface UserMapper extends BaseMapper<User> {}
5、测试
@Testvoid MybatisPlusTest(){ //User user = userMapper.selectById(1); List<User> users = userMapper.selectList(null); for (User user : users) { log.info(String.valueOf(user)); }}
6、ServiceImpl使用提供好的接口
UserService需要继承IService
UserServiceImpl 继承实现类extends ServiceImpl<UserMapper,User>
@Servicepublic class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {}public interface UserService extends IService<User> {}
在controller中:
userServie.函数名
二、NoSQL
Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件。
1、Redis自动配置
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
自动配置:
- RedisAutoConfiguration 自动配置类。RedisProperties 属性类 --> spring.redis.xxx是对redis的配置
- 连接工厂是准备好的。LettuceConnectionConfiguration、JedisConnectionConfiguration
- 自动注入了RedisTemplate<Object, Object> : xxxTemplate;
- 自动注入了StringRedisTemplate;k:v都是String
- key:value
- 底层只要我们使用 StringRedisTemplate、****RedisTemplate就可以操作redis
redis环境搭建
1、阿里云按量付费redis。经典网络
2、申请redis的公网连接地址
3、修改白名单 允许0.0.0.0/0 访问
2、RedisTemplate与Lettuce
@Test void testRedis(){ ValueOperations<String, String> operations = redisTemplate.opsForValue(); operations.set("hello","world"); String hello = operations.get("hello"); System.out.println(hello); }
3、切换至jedis
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency><!-- 导入jedis--> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>spring: redis: host: r-bp1nc7reqesxisgxpipd.redis.rds.aliyuncs.com port: 6379 password: lfy:Lfy123456 client-type: jedis jedis: pool: max-active: 10
SpringBoot笔记(6)的更多相关文章
- SpringBoot笔记十六:ElasticSearch
目录 ElasticSearch官方文档 ElasticSearch安装 ElasticSearch简介 ElasticSearch操作数据,RESTful风格 存储 检查是否存在 删除 查询 更新 ...
- SpringBoot笔记一
1 开始 1.1 spring介绍 Spring Boot使开发独立的,产品级别的基于Spring的应用变得非常简单,你只需"just run". 我们为Spring平台及第三方库 ...
- 【SpringBoot笔记】SpringBoot整合Druid数据连接池
废话少说,按SpringBoot的老套路来. [step1]:添加依赖 <!-- 数据库连接池 --> <dependency> <groupId>com.alib ...
- SpringBoot笔记十七:热部署
目录 什么是热部署 Devtools热部署 什么是热部署 热部署,就是在应用正在运行的时候升级软件,却不需要重新启动应用. 举个例子,王者荣耀的更新有时候就是热部署,热更新,就是他提示你更新,更新40 ...
- SpringBoot笔记十四:消息队列
目录 什么是消息队列 消息队列的作用 异步通信 应用解耦 流量削峰 RabbitMQ RabbitMQ流程简介 RabbitMQ的三种模式 安装RabbitMQ RabbitMQ交换器路由和队列的创建 ...
- SpringBoot笔记十三:引入webjar资源和国际化处理
目录 什么是webjar 怎么使用webjar 国际化 新建国际化配置文件 配置配置文件 使用配置文件 我们先来看一个html,带有css的,我们就以这个为准来讲解. 资源可以去我网盘下载 链接:ht ...
- springboot笔记1(转载于puresmile)
构建微服务:Spring boot 入门篇 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框 ...
- SpringBoot笔记
官网: http://springboot.fun/ 收集到一个比较全的: https://blog.csdn.net/xiaoyu411502/article/details/52474037 Id ...
- springboot笔记05——profile多环境配置切换
前言 一个应用程序从开发到上线,往往需要经历几个阶段,例如开发.测试.上线.每个阶段所用到的环境的配置可能都是不一样的,Springboot 应用可以很方便地在各个环境中对配置进行切换.所以,今天主要 ...
- springboot笔记09——使用aop
什么是AOP? aop(Aspect Oriented Programming)面向切面编程,是OOP(Object-Oriented Programing,面向对象编程)的补充和完善.OOP引入封装 ...
随机推荐
- Python 和 C/C++ 拓展程序如何性能优化?看这一篇文就够
作者:王璐璐 | 旷视 MegEngine 架构师 一. 背景 在 MegEngine imperative runtime 的早期开发中,我们面临着一些的性能优化问题.除了一些已知需要重构的地方(早 ...
- Android开发音视频方向学习路线及资源分享,学完还怕什么互联网寒冬?
接触Android音视频这一块已经有一段时间了,跟普通的应用层开发相比,的确更花费精力.期间为了学习音视频的录制,编码,处理也看过大大小小的几十个项目.总体感觉就是知识比较零散,对刚入门的朋友比较不友 ...
- Map 与 unordered_map 横向与纵向测试,附带原始数据与测试程序
写程序时,面临用Map还是unordered_map,总是很纠结,于是写了个程序进行测试 Map 与 unordered_map 横向与纵向测试,附带原始数据与测试程序 简单数据(4 Byte) 首先 ...
- MapReduce框架原理-MapTask和ReduceTask工作机制
MapTask工作机制 并行度决定机制 1)问题引出 maptask的并行度决定map阶段的任务处理并发度,进而影响到整个job的处理速度.那么,mapTask并行任务是否越多越好呢? 2)MapTa ...
- 算法竞赛中的常用JAVA API :HashMap 和 TreeMap(转载)
算法竞赛中的常用JAVA API :HashMap 和 TreeMap 摘要 本文主要介绍Map接口下的HashMap和TreeMap. HashMap HashMap是基于哈希表的 Map 接口的实 ...
- React脚手架配置代理
react脚手架配置代理 方法一 在package.json中追加如下配置 "proxy":"http://localhost:5000" 说明: 优点:配置简 ...
- LiteFlow 2.6.0版本发行注记,项目逻辑解耦的利器
前言 自从LiteFlow 2.5.X版本发布依赖,陆续经历了10个小版本的迭代.社区群也稳固增长,每天都有很多小伙伴在问我问题. 但是我发现最多人问我的还是:什么时候能支持界面编排? 从LiteFL ...
- SpringMVC学习04(数据处理及跳转)
4.数据处理及跳转 4.1结果跳转方式 4.1.1 ModelAndView 设置ModelAndView对象 , 根据view的名称 , 和视图解析器跳到指定的页面 . 页面 : {视图解析器前缀} ...
- 我写一篇文章就是要批评CSDN! 因为蓝湖3.0的更新
对于开发者,经常会使用,学习到各种环境语言和工具 我们不只是在不断的在搬运知识,更多时候我们也是在 分享我们学到的"新知识", 当我们有幸觉得自己发现了新的知识与技术时,作为分享者 ...
- BaiduSpider:爬取百度的利器
视频链接:https://www.zhihu.com/zvideo/1272864710321516544 BaiduSpider是一个能够爬取百度搜索结果的Python爬虫,轻量但强大.目前支持百度 ...