SpringBoot 之 数据访问

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
简介: SpringBoot 之 数据访问

3、数据访问

3.1、SQL

3.1.1、数据源的自动配置-HikariDataSource

① 导入JDBC场景

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

② 分析自动配置

自动配置的类


DataSourceAutoCOnfiguration:数据源的自动配置

修改数据源相关的配置:spring.datasource

数据库连接池的配置,是自己容器中没有DataSource才自动配置的

底层配置好的连接池是:HikariDataSource

DataSourceTransactionManagerAutoConfiguration:事务管理器的自动配置

JdbcTemplateAutoConfiguration:JdbcTemplate的自动配置,可以来对数据库进行crud

可以修改这个配置项 @ConfigurationProperties(prefix = “spring.jdbc”) 来修改JbdcTemplate

@Bean @Primary JdbcTemplate 容器中有这个组件

JndiDataSourceAutoConfiguration:jndi 的自动配置

XADataSourceAutoConfiguration:分布式事务相关的

③ 修改配置项

spring:
  datasource:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/info
      username: root
      password: jc951753

④ 测试

@Slf4j
@SpringBootTest
class Springboot02WebAdminApplicationTests {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Test
    void contextLoads() {
        // jdbcTemplate.queryForList("select * from account_tbl");
        Long aLong = jdbcTemplate.queryForObject("select count(*) from card", Long.class);
        log.info("记录总数:{}",aLong);
    }
}

3.1.2、使用Druid数据源

① 官方地址

Github官方地址:https://github.com/alibaba/druid

整合第三方技术的两种方式

自定义

找starter

② 自定义方式

创建数据源

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.13</version>
</dependency>
<!-- Spring原生使用方法如下: -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
    destroy-method="close">
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
    <property name="maxActive" value="20" />
    <property name="initialSize" value="1" />
    <property name="maxWait" value="60000" />
    <property name="minIdle" value="1" />
    <property name="timeBetweenEvictionRunsMillis" value="60000" />
    <property name="minEvictableIdleTimeMillis" value="300000" />
    <property name="testWhileIdle" value="true" />
    <property name="testOnBorrow" value="false" />
    <property name="testOnReturn" value="false" />
    <property name="poolPreparedStatements" value="true" />
    <property name="maxOpenPreparedStatements" value="20" />

StatViewServlet

StatViewServlet用途包括:

提供监控信息展示的 HTML 页面

提供监控信息的 JSON API

<servlet>
    <servlet-name>DruidStatView</servlet-name>
    <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>DruidStatView</servlet-name>
    <url-pattern>/druid/*</url-pattern>
</servlet-mapping>

StatFilter

用于统计监控信息 如 SQL 监控、URL 监控

<!-- 需要给数据源中配置如下属性;可以允许多个filter,多个用,分割;如: -->
<property name="filters" value="stat,slf4j" />

③ 使用官方starter方式

引入 druid-starter

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.9</version>
</dependency>

分析自动配置


扩展配置项 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的配置

配置示例

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db_a
    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: 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

3.1.3、整合MyBatis操作

官方地址:https://github.com/mybatis

SpringBoot官方的starter:spring-boot-starter-*

第三方的:*-spring-boot-starter

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

① 配置模式

全局配置文件

SqlSessionFactory:自动配置好了

SqlSession:自动配置了 SqlSessionTemplate 组合了 SqlSession

@Import(AutoConfiguredMapperScannerRegistrar.class)

Mapper:只需要我们写操作 MyBatis 的接口标准了 @Mapper 就会被自动扫描进来

在配置文件中进行配置

mybatis:
  # 全局配置文件
  config-location: classpath:mybatis/mybatis-config.xml
  # 映射文件位置
  mapper-locations: classpath:mybatis/mapper/*.xml

Mapper 接口与映射文件的绑定

<?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 namespace="com.jingchao.admin.mapper.AccountMapper">
  <select id="getAccount" resultType="com.jingchao.admin.bean.Account">
    select * from account where id = #{id}
  </select>
</mapper>

步骤


导入 mybatis 官方starter


编写 mapper 接口,标注 @Mapper 注解


编写 SQL 映射文件并绑定 mapper 接口


在application.yml 中指定 Mapper 配置文件的位置,以及指定全局配置文件的信息(建议配置在 mybaits.configuration)

mybatis:
  #(不推荐) config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
  #(推荐) 指定全局配置文件中的配置项(不能使用上面的mybatis-config文件了)
  configuration: 
    map-underscore-to-camel-case: true

② 注解模式

@Mapper
public interface CityMapper {
    @Select("select * from city where id = #{id}")
    public City getCityById(Integer id);
}

③ 混合模式

@Mapper
public interface CityMapper {
    @Select("select * from city where id = #{id}")
    public City getCityById(Integer id);
    // @Insert("insert into city(`name`,`state`,`country`) values(#{name},#{state},#{country})")
    // @Options(useGeneratedKeys = true, keyProperty = "id")
    public void insertCity(City city);
}
<?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 namespace="com.jingchao.admin.mapper.CityMapper">
  <insert id="insertCity" useGeneratedKeys="true" keyProperty="id">
    insert into city(`name`,`state`,`country`) values(#{name},#{state},#{country})
  </insert>
</mapper>

步骤


引入 mybaits-starter

配置 application.yml ,指定 mapper-location 位置

编写 Mapper 接口方法,标注 @Mapper 注解

简单方法直接注解方式

复杂方法编写 mapper映射文件进行绑定

@MapperScan(“com.jingchao.admin.mapper”)简化,其他接口就可以不用标注 @Mapper 注解


3.1.4、整合MyBatis-Plus完成 CRUD

① MyBaits-Plus 简介

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。


mybatis plus 官网


建议安装 MybatisX 插件


② 整合MyBatis-Plus

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>

自动配置


MybatisPlusAutoConfiguration 配置类,MybatisPlusProperties 配置项绑定。mybatis-plus:xxx 就是对****mybatis-plus的定制

SqlSessionFactory 自动配置好。底层是容器中默认的数据源

mapperLocations 自动配置好的。有默认值。classpath*:/mapper/**/*.xml;任意包的类路径下的所有mapper文件夹下任意路径下的所有xml都是sql映射文件。 建议以后sql映射文件,放在 mapper下

容器中也自动配置好了 SqlSessionTemplate

@Mapper 标注的接口也会被自动扫描;建议直接 @MapperScan(“com.atguigu.admin.mapper”) 批量扫描就行

优点


只需要我们的 Mapper 继承 BaseMapper 就可以拥有 crud 能力

③ CRUD功能

    @GetMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable("id") Long id,
                             @RequestParam(value = "pn",defaultValue = "1")Integer pn,
                             RedirectAttributes ra){
        userService.removeById(id);
        ra.addAttribute("pn",pn);
        return "redirect:/dynamic_table";
    }
    @GetMapping("/dynamic_table")
    public String dynamic_table(@RequestParam(value="pn",defaultValue = "1") Integer pn,Model model){
        //表格内容的遍历
//        response.sendError
//     List<User> users = Arrays.asList(new User("zhangsan", "123456"),
//                new User("lisi", "123444"),
//                new User("haha", "aaaaa"),
//                new User("hehe ", "aaddd"));
//        model.addAttribute("users",users);
//
//        if(users.size()>3){
//            throw new UserTooManyException();
//        }
        //从数据库中查出user表中的用户进行展示
        //构造分页参数
        Page<User> page = new Page<>(pn, 2);
        //调用page进行分页
        Page<User> userPage = userService.page(page, null);
//        userPage.getRecords()
//        userPage.getCurrent()
//        userPage.getPages()
        model.addAttribute("users",userPage);
        return "table/dynamic_table";
    }
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {}
public interface UserService extends IService<User> {}

3.2、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)。


3.2.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环境搭建:


阿里云按量付费redis。经典网络

申请redis的公网连接地址

修改白名单 允许0.0.0.0/0 访问


3.2.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 = " + hello);
}

3.2.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: 127.0.0.1
    port: 6379
    client-type: jedis
    lettuce:
      pool:
        max-active: 10
        min-idle: 5


相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
2月前
|
前端开发 Java API
SpringBoot整合Flowable【06】- 查询历史数据
本文介绍了Flowable工作流引擎中历史数据的查询与管理。首先回顾了流程变量的应用场景及其局限性,引出表单在灵活定制流程中的重要性。接着详细讲解了如何通过Flowable的历史服务API查询用户的历史绩效数据,包括启动流程、执行任务和查询历史记录的具体步骤,并展示了如何将查询结果封装为更易理解的对象返回。最后总结了Flowable提供的丰富API及其灵活性,为后续学习驳回功能做了铺垫。
117 0
SpringBoot整合Flowable【06】- 查询历史数据
|
7天前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
1月前
|
Java 关系型数据库 MySQL
SpringBoot 通过集成 Flink CDC 来实时追踪 MySql 数据变动
通过详细的步骤和示例代码,您可以在 SpringBoot 项目中成功集成 Flink CDC,并实时追踪 MySQL 数据库的变动。
254 43
|
5月前
|
人工智能 自然语言处理 前端开发
SpringBoot + 通义千问 + 自定义React组件:支持EventStream数据解析的技术实践
【10月更文挑战第7天】在现代Web开发中,集成多种技术栈以实现复杂的功能需求已成为常态。本文将详细介绍如何使用SpringBoot作为后端框架,结合阿里巴巴的通义千问(一个强大的自然语言处理服务),并通过自定义React组件来支持服务器发送事件(SSE, Server-Sent Events)的EventStream数据解析。这一组合不仅能够实现高效的实时通信,还能利用AI技术提升用户体验。
461 2
|
2月前
|
XML Java 应用服务中间件
Spring Boot 两种部署到服务器的方式
本文介绍了Spring Boot项目的两种部署方式:jar包和war包。Jar包方式使用内置Tomcat,只需配置JDK 1.8及以上环境,通过`nohup java -jar`命令后台运行,并开放服务器端口即可访问。War包则需将项目打包后放入外部Tomcat的webapps目录,修改启动类继承`SpringBootServletInitializer`并调整pom.xml中的打包类型为war,最后启动Tomcat访问应用。两者各有优劣,jar包更简单便捷,而war包适合传统部署场景。需要注意的是,war包部署时,内置Tomcat的端口配置不会生效。
622 17
Spring Boot 两种部署到服务器的方式
|
2月前
|
存储 前端开发 Java
SpringBoot整合Flowable【05】- 使用流程变量传递业务数据
本文介绍了如何使用Flowable的流程变量来管理绩效流程中的自定义数据。首先回顾了之前的简单绩效流程,指出现有流程缺乏分数输入和保存步骤。接着详细解释了流程变量的定义、分类(运行时变量和历史变量)及类型。通过具体代码示例展示了如何在绩效流程中插入全局和局部流程变量,实现各节点打分并维护分数的功能。最后总结了流程变量的使用场景及其在实际业务中的灵活性,并承诺将持续更新Flowable系列文章,帮助读者更好地理解和应用Flowable。 简要来说,本文通过实例讲解了如何利用Flowable的流程变量功能优化绩效评估流程,确保每个环节都能记录和更新分数,同时提供了全局和局部变量的对比和使用方法。
169 0
SpringBoot整合Flowable【05】- 使用流程变量传递业务数据
|
4月前
|
JSON JavaScript 前端开发
springboot中使用knife4j访问接口文档的一系列问题
本文作者是一位自学前端两年半的大一学生,分享了在Spring Boot项目中使用Knife4j遇到的问题及解决方案,包括解决Swagger请求404错误、JS错误等,详细介绍了依赖升级、注解替换及配置修改的方法。
649 1
|
4月前
|
SQL 前端开发 关系型数据库
SpringBoot使用mysql查询昨天、今天、过去一周、过去半年、过去一年数据
SpringBoot使用mysql查询昨天、今天、过去一周、过去半年、过去一年数据
123 9
|
4月前
|
存储 运维 安全
Spring运维之boot项目多环境(yaml 多文件 proerties)及分组管理与开发控制
通过以上措施,可以保证Spring Boot项目的配置管理在专业水准上,并且易于维护和管理,符合搜索引擎收录标准。
123 2
|
4月前
|
JSON JavaScript 前端开发
springboot中使用knife4j访问接口文档的一系列问题
本文介绍了在Spring Boot项目中使用Knife4j访问接口文档时遇到的一系列问题及其解决方案。作者首先介绍了自己是一名自学前端的大一学生,熟悉JavaScript和Vue,正在向全栈方向发展。接着详细说明了如何解决Swagger请求404错误,包括升级Knife4j依赖、替换Swagger 2注解为Swagger 3注解以及修改配置类中的代码。最后,针对报JS错误的问题,提供了删除消息转换器代码的解决方法。希望这些内容能对读者有所帮助。
717 5