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-pcl可视化点云工具(windows和ubuntu18.04安装及测试)

    python-pcl可视化点云工具(windows和ubuntu18.04安装及测试)

    2020年11月8日
    392
  • SIFT–尺度空间、高斯金字塔

    SIFT–尺度空间、高斯金字塔尺度空间高斯金字塔高斯模糊下采样高斯金字塔的构造过程差分高斯金字塔构造过程SIFT成名已久,但理解起来还是很难的,一在原作者Lowe的论文对细节提到的非常少,二在虽然网上有许多相应博文,但这些博文云里雾里,非常头疼,在查看了许多资料了,下面贴出我自己的一些理解,希望有所帮助。Lowe把SIFT分为四个阶段:构建尺度空间、关键点的定位、方向分配、特征描述符。下面分别从这四个阶段来阐述。尺度空

    2022年10月14日
    4
  • 解决:java.lang.AbstractMethodError: null

    解决:java.lang.AbstractMethodError: nullspringboot2.x整合sqlserver使用jtds连接池连数据库的时候出现异常2017-02-1512:12:23.955WARN14844—[main]ationConfigEmbeddedWebApplicationContext:Exceptionencounteredduringcontextinitializ…

    2022年6月2日
    374
  • 秒杀多线程第四篇 一个经典的多线程同步问题

    秒杀多线程第四篇 一个经典的多线程同步问题

    2021年11月30日
    46
  • 安全-流量劫持形成的原因

    流量劫持,这种古老的攻击沉寂了一段时间后,最近又开始闹的沸沸扬扬。众多知名品牌的路由器相继爆出存在安全漏洞,引来国内媒体纷纷报道。只要用户没改默认密码,打开一个网页甚至帖子,路由器配置就会被暗中修改。互联网一夜间变得岌岌可危。详解流量劫持的形成原因攻击还是那几种攻击,报道仍是那千篇一律的砖家提醒,以至于大家都麻木了。早已见惯运营商的各种劫持,频繁的广告弹窗,大家也无可奈何。这么多年也没出现…

    2022年4月9日
    43
  • SpringBoot是什么?干嘛用的?(新手入门篇)

    SpringBoot是什么?干嘛用的?(新手入门篇)SpringBoot是干哈的介绍:springboot是由Pivotal团队提供的全新框架。spring的出现是为了解决企业级开发应用的复杂性,spring的通过注册bean的方式来管理类,但是随着业务的增加,使用xml配置bean的方式也显得相当繁琐,所以springboot就是为了解决spring配置繁琐的问题而诞生的,并且近几年来非常流行开启我的第一个HelloSpringBoot!开启方式根据https://start.spring.io网址创建一个springboot项目

    2025年7月21日
    5

发表回复

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

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