SpringBoot笔记(6)

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

配置项列表https://github.com/alibaba/druid/wiki/DruidDataSource%E9%85%8D%E7%BD%AE%E5%B1%9E%E6%80%A7%E5%88%97%E8%A1%A8

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 的基础上只做增强不做改变,为简化开发、提高效率而生。

mybatis plus 官网

建议安装 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
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/115186.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Python如何生成可执行的.exe文件

    Python如何生成可执行的.exe文件为什么要生成可执行文件:不需要安装对应的编程环境可以将你的应用闭源用户可以方便、快捷的直接使用打包工具pyinstaller一.pyinstaller简介Python是一个脚本语言,被解释器解释执行。它的发布方式:.py文件:对于开源项目或者源码没那么重要的,直接提供源码,需要使用者自行安装Python并且安装依赖的各种库。(Python官方的各种安装包就是这样做的).pyc文件…

    2022年5月25日
    24
  • 通过pycharm安装python_pycharm编译器安装教程

    通过pycharm安装python_pycharm编译器安装教程python环境的安装与编译器的安装python下载网址python官网:https://www.python.org/python的安装我们对Markdown编辑器进行了一些功能拓展与语法支持,除了标准的Markdown编辑器功能,我们增加了如下几点新功能,帮助你用它写博客:全新的界面设计,将会带来全新的写作体验;在创作中心设置你喜爱的代码高亮样式,Markdown将代码片显示选择的高亮样式进行展示;增加了图片拖拽功能,你可以将本地的图片直接拖拽到编辑区域直接展示;全新的Ka

    2022年8月25日
    9
  • 哈佛幸福课笔记中篇

    哈佛幸福课笔记中篇改变一生的课:哈佛幸福课笔记中篇第9课积极情绪第10课如何去改变第11课养成良好习惯第12课写日记第13课面对压力第14课过犹不及第15课完美主义第16课享受过程链接:哈佛大学公开课:幸福课.《哈佛幸福课》是改变我生活最大的一项事物,没有之一。我学习了5遍幸福课,并且用过去6年的时间去尝试它践行它,感觉完全改变了我的生活。第9课积极情绪1.感激练习,每天去做才能养成习惯,那样才能改变思维。每天变化,思考不同的方向去做。爱默生:如果星星每千年闪烁一次,我们都会仰视赞美这个世界的

    2022年7月25日
    8
  • ov7725摄像头模块_寄存器和内存

    ov7725摄像头模块_寄存器和内存上图是OV7725实现的整体框架,有点丑。FPGA描述SCCB时序,完成OV7725的配置,配置完成之后,OV7725sensor输出PCLK和href,vsync以及cmos_data信号。经过格式的转换单元,将格式转换后的数据送给SDRAM单元,最终实现VGA/LCD/上位机显示。 之前已经提及过,SCCB接口主要实现sensor内部各种寄存器的配置,如AGC,AWB,gama,c

    2025年12月4日
    6
  • Jenkins配置Coding Webhook

    Jenkins配置Coding WebhookJenkins配置CodingWebhook1.安装插件2.创建项目3.Coding设置ServiceHook1.安装插件需要重启Jenkins2.创建项目这里选择自由风格添加git注意:WebHook地址是你http://jenkins地址/coding/项目名设置运行脚本3.Coding设置ServiceHook使用CodingWebhookPlugin过时问题.使用插件后无法保存配置文件

    2022年5月5日
    79
  • Kali WPScan的使用(WordPress扫描工具)

    Kali WPScan的使用(WordPress扫描工具)一 WPScan 简介 WordPress 网站介绍 WordPress 是全球流行的博客网站 全球有上百万人使用它来搭建博客 他使用 PHP 脚本和 Mysql 数据库来搭建网站 Wordpress 作为三大建站模板之一 在全世界范围内有大量的用户 这也导致白帽子都会去跟踪 WordPress 的安全漏洞 Wordpress 自诞生起也出现了很多漏洞 Wordpress 还可以使用插件 主题 于

    2025年9月22日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号