SpringBoot 之 数据访问

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 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
相关文章
|
3天前
|
Java
Springboot 导出word,动态填充表格数据
Springboot 导出word,动态填充表格数据
|
3天前
|
Java 数据库连接 mybatis
springboot访问jsp页面变成直接下载?
springboot访问jsp页面变成直接下载?
81 0
|
3天前
|
缓存 Java Sentinel
Springboot 中使用 Redisson+AOP+自定义注解 实现访问限流与黑名单拦截
Springboot 中使用 Redisson+AOP+自定义注解 实现访问限流与黑名单拦截
|
3天前
|
SQL Java 数据库
springboot用户创建的业务数据只能是同一组织能看的见
springboot用户创建的业务数据只能是同一组织能看的见
|
2天前
|
SQL Java 调度
SpringBoot使用@Scheduled定时任务录入将要过期任务数据
SpringBoot使用@Scheduled定时任务录入将要过期任务数据
|
3天前
|
前端开发 关系型数据库 MySQL
SpringBoot-----从前端更新数据到MySql数据库
SpringBoot-----从前端更新数据到MySql数据库
10 1
|
3天前
|
NoSQL Java Redis
springboot之RedisTemplate的访问单机,哨兵,集群模式
以上是配置RedisTemplate以连接到单机、哨兵和集群模式的示例。在实际应用中,还可以根据需求配置连接池、序列化方式、超时等其他参数。
36 0
|
3天前
|
Java Spring
spring boot访问接口报500
spring boot访问接口报500
13 2
|
3天前
|
JSON JavaScript Java
从前端Vue到后端Spring Boot:接收JSON数据的正确姿势
从前端Vue到后端Spring Boot:接收JSON数据的正确姿势
25 0
|
3天前
|
前端开发 JavaScript Java
SpringBoot解决跨域访问的问题
本文介绍了跨域访问的概念及其解决方案。同源策略规定浏览器限制不符合协议、Host和端口的请求,导致跨域访问被禁止。为解决此问题,文中提出了三种策略:1) 前端利用HTML标签的特性(如script、iframe)和JSONP、postMessage规避同源策略;2) 通过代理,如nginx或nodejs中间件,使得所有请求看似来自同一源;3) CORS(跨域资源共享),通过设置HTTP响应头允许特定跨域请求。在SpringBoot中,实现CORS有四种方式,包括使用CorsFilter、重写WebMvcConfigurer、CrossOrigin注解以及直接设置响应头。