SpringBoot 之 数据访问

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
简介: 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


相关文章
|
2月前
|
JSON Java 数据格式
Spring Boot返回Json数据及数据封装
在Spring Boot中,接口间及前后端的数据传输通常使用JSON格式。通过@RestController注解,可轻松实现Controller返回JSON数据。该注解是Spring Boot新增的组合注解,结合了@Controller和@ResponseBody的功能,默认将返回值转换为JSON格式。Spring Boot底层默认采用Jackson作为JSON解析框架,并通过spring-boot-starter-json依赖集成了相关库,包括jackson-databind、jackson-datatype-jdk8等常用模块,简化了开发者对依赖的手动管理。
372 3
|
6月前
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——封装统一返回的数据结构
本文介绍了在Spring Boot中封装统一返回的数据结构的方法。通过定义一个泛型类`JsonResult&lt;T&gt;`,包含数据、状态码和提示信息三个属性,满足不同场景下的JSON返回需求。例如,无数据返回时可设置默认状态码&quot;0&quot;和消息&quot;操作成功!&quot;,有数据返回时也可自定义状态码和消息。同时,文章展示了如何在Controller中使用该结构,通过具体示例(如用户信息、列表和Map)说明其灵活性与便捷性。最后总结了Spring Boot中JSON数据返回的配置与实际项目中的应用技巧。
540 0
|
6月前
|
JSON Java fastjson
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——使用 fastJson 处理 null
本文介绍如何使用 fastJson 处理 null 值。与 Jackson 不同,fastJson 需要通过继承 `WebMvcConfigurationSupport` 类并覆盖 `configureMessageConverters` 方法来配置 null 值的处理方式。例如,可将 String 类型的 null 转为 &quot;&quot;,Number 类型的 null 转为 0,避免循环引用等。代码示例展示了具体实现步骤,包括引入相关依赖、设置序列化特性及解决中文乱码问题。
321 0
|
6月前
|
JSON Java fastjson
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——Spring Boot 默认对Json的处理
本文介绍了在Spring Boot中返回Json数据的方法及数据封装技巧。通过使用`@RestController`注解,可以轻松实现接口返回Json格式的数据,默认使用的Json解析框架是Jackson。文章详细讲解了如何处理不同数据类型(如类对象、List、Map)的Json转换,并提供了自定义配置以应对null值问题。此外,还对比了Jackson与阿里巴巴FastJson的特点,以及如何在项目中引入和配置FastJson,解决null值转换和中文乱码等问题。
919 0
|
8月前
|
前端开发 Java API
SpringBoot整合Flowable【06】- 查询历史数据
本文介绍了Flowable工作流引擎中历史数据的查询与管理。首先回顾了流程变量的应用场景及其局限性,引出表单在灵活定制流程中的重要性。接着详细讲解了如何通过Flowable的历史服务API查询用户的历史绩效数据,包括启动流程、执行任务和查询历史记录的具体步骤,并展示了如何将查询结果封装为更易理解的对象返回。最后总结了Flowable提供的丰富API及其灵活性,为后续学习驳回功能做了铺垫。
600 0
SpringBoot整合Flowable【06】- 查询历史数据
|
11月前
|
人工智能 自然语言处理 前端开发
SpringBoot + 通义千问 + 自定义React组件:支持EventStream数据解析的技术实践
【10月更文挑战第7天】在现代Web开发中,集成多种技术栈以实现复杂的功能需求已成为常态。本文将详细介绍如何使用SpringBoot作为后端框架,结合阿里巴巴的通义千问(一个强大的自然语言处理服务),并通过自定义React组件来支持服务器发送事件(SSE, Server-Sent Events)的EventStream数据解析。这一组合不仅能够实现高效的实时通信,还能利用AI技术提升用户体验。
783 2
|
6月前
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
7月前
|
Java 关系型数据库 MySQL
SpringBoot 通过集成 Flink CDC 来实时追踪 MySql 数据变动
通过详细的步骤和示例代码,您可以在 SpringBoot 项目中成功集成 Flink CDC,并实时追踪 MySQL 数据库的变动。
1803 45
|
8月前
|
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的端口配置不会生效。
2174 17
Spring Boot 两种部署到服务器的方式
|
6月前
|
Java 数据库 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——指定项目配置文件
在实际项目中,开发环境和生产环境的配置往往不同。为简化配置切换,可通过创建 `application-dev.yml` 和 `application-pro.yml` 分别管理开发与生产环境配置,如设置不同端口(8001/8002)。在 `application.yml` 中使用 `spring.profiles.active` 指定加载的配置文件,实现环境快速切换。本节还介绍了通过配置类读取参数的方法,适用于微服务场景,提升代码可维护性。课程源码可从 [Gitee](https://gitee.com/eson15/springboot_study) 下载。
234 0