Spring Boot 实践之六 Spring Boot数据访问(Sping Boot整合MyBatis/Sping Boot整合JPA/Sping Boot整合Redis)

​ 在开发中,通常会涉及到对数据库的数据进行操作,Spring Boot在简化项目开发以及实现自动化配置的基础上,对关系型数据库和非关系型数据库的访问操作都提供了非常好的整合支持。

​ 本章,将对Spring Boot的数据访问进行介绍,并对常用的数据操作框架进行整合讲解。

3.1 Spring Boot数据访问概述

Spring Boot默认采用整合SpringData的方式统一处理数据访问层,通过添加大量自动配置,引入各种数据访问模板xxxTemplate以及统一的Repository接口,从而达到简化数据访问层的操作。

  • Spring Boot提供的常见数据库依赖启动器

    名称 对应数据库
    spring-boot-starter-data-jpa •Spring Data JPA •Hibernate
    spring-boot-starter-data-mongodb •MongoDB •Spring Data MongoDB
    spring-boot-starter-data-neo4j •Neo4j图数据库 •Spring Data Neo4j
    spring-boot-starter-data-redis •Redis
  • 官方没有提供的数据库,如Mybatis,其开发团队自己适配了Spring Boot,提供了mybatis-spring-boot-starter依束启动器实现数据访问操作。

3.2 Sping Boot整合MyBatis

MyBatis是一款优秀的持久层框架,支持定制化SQL、存储过程以及高级映射,避免了几乎所有的JDBC代码和手动设置参数以及获取结果集:

3.2.1 基础环境搭建
  • 步骤1:MYSQL安装准备,这里使用phpstudy直接准备,默认端口3306,用户名和密码都是root,正常运行效果如图。
    phpstudy运行界面

  • 步骤2:数据准备。可以使用http://localhost/phpymyamdin(如果网页端口非80端口,比如88端口,需要改为实际端口,http://localhost:88/phpymyamdin)访问数据库并创建数据,也可以使用SQLyog访问,这里介绍SQLyog访问方法。

    • 1)安装SQLyog
    • 2)连接到我的SQL主机
      SQLyog运行界面
      • 3)创建数据库:springbootdata,命令:CREATE DATABASE springbootdata;
        在这里插入图片描述
  • 4)创建数据表 t_article,操作方法同上。

    CREATE TABLE `t_article` (
      `id` INT(20) NOT NULL AUTO_INCREMENT COMMENT '文章id',
      `title` VARCHAR(200) DEFAULT NULL COMMENT '文章标题',
      `content` LONGTEXT COMMENT '文章内容',
      PRIMARY KEY (`id`)
    ) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    
    1. t_article表中插入数据,操作方法同上。
    INSERT INTO `t_article` VALUES ('1', 'Spring Boot基础入门', '从入门到精通讲解...');
    INSERT INTO `t_article` VALUES ('2', 'Spring Cloud基础入门', '从入门到精通讲解...');
    
  • 6)创建数据表t_comment,操作方法同上。代码:

    CREATE TABLE `t_comment` (
      `id` INT(20) NOT NULL AUTO_INCREMENT COMMENT '评论id',
      `content` LONGTEXT COMMENT '评论内容',
      `author` VARCHAR(200) DEFAULT NULL COMMENT '评论作者',
      `a_id` INT(20) DEFAULT NULL COMMENT '关联的文章id',
      PRIMARY KEY (`id`)
    ) ENGINE=INNODB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    
  • 6)t_comment表中插入数据:

    INSERT INTO `t_comment` VALUES ('1', '很全、很详细', '狂奔的蜗牛', '1');
    INSERT INTO `t_comment` VALUES ('2', '赞一个', 'tom', '1');
    INSERT INTO `t_comment` VALUES ('3', '很详细', 'kitty', '1');
    INSERT INTO `t_comment` VALUES ('4', '很好,非常详细', '张三', '1');
    INSERT INTO `t_comment` VALUES ('5', '很不错', '张杨', '2');
    

    完成后效果如图:
    在这里插入图片描述

  • 步骤3:创建项目,引入MySQL和MyBatis的依赖启动器

    1)使用Spring Initializr方式创建一个名为chapter03的Spring Boot项目(要求能联网)
    在这里插入图片描述
    2)设置项目的Group,Artifact和Package,按next
    在这里插入图片描述
    3)在Dependencies依赖中选择SQL模块中的MySQL和MyBatis依赖,点击next
    在这里插入图片描述
    4)设置存储路径,按Finish,完成项目创建。

  • 步骤3:编写配置文件

    1)创建在com.itheima下创建包domain,再创建实体类Comment

  1. 为实体类Comment创建4个变量

    package com.itheima.domain;
    
    public class Comment {
         
        private Integer id;
        private String content;
        private String author;
        private Integer aId;
    }
    

    在Comment方法空白处,按ALT+Insert,生成Getter和Setter方法.

  • 同样方法在domain,创建实体类Article,为实体类Article创建4个变量:

    public class Article {
         
        private Integer id;
        private String title;
        private String content;
        private List<Comment> commentList;}//一篇文章存在多个评论,所在这里使用集合
    
    

    在Article方法空白处,按ALT+Insert,生成各变量的Getter和Setter方法,效果如图:
    在这里插入图片描述

    • 在application.properties配置文件中进行数据库连接配置。
    spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC
    spring.datasource.username=root
    spring.datasource.password=root
    
    

    说明:第一行为驱动,第二行为数据库连接地址,3306一般是数据库默认端口,springbootdata为数据库名。用户名和 密码请按实际填写。

  • 步骤4:Spring Boot 1.x默认使用的是tomcat.jdbc数据库,Spring Boot 2.X版本默认使用的是hikari数据源。其他数据源需要另行配置。这里演示阿里巴巴的Druid数据源配置

    • 1)pom.xml文件中添加Druid数据源的依赖启动器,示例代码如下:

      <!--阿里巴巴druid数据源依赖-->
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid-spring-boot-starter</artifactId>
          <version>1.1.10</version>
      </dependency>
      
      
    • 2)上述启动器默认初始化了一些运行参考,如果需要修改,则必须在全局配置文件中修改,示例如图。

      #添加并配置第三方数据源Druid
      #数据源类型
      spring.datasource.type = com.alibaba.druid.pool.DruidDataSource
      #初始化连接数
      spring.datasource.initialSize=20
      #最小空闲数
      spring.datasource.minIdle=10
      #最大连接数
      spring.datasource.maxActive=100
      
      

在这里插入图片描述

    • 说明:因为在Spring Boot提供的数据源自动配置类中没有initialSize、minIdle和maxActive没有与这些参数对应的默认属性,所以这些设置的属性值 无法识别和生效。底纹为黄色显示 。为此,还需要编写一个自定义配置类。将配置文件中的属性注入到Druid数据源属性中。

    • 3)在com.itheima下创建config包,并在该包下创建一个自定义配置类对Druid数据源属性值 进行注入。内容如下:

      package com.itheima.config;
      
      import com.alibaba.druid.pool.DruidDataSource;
      import org.springframework.boot.context.properties.ConfigurationProperties;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      
      import javax.sql.DataSource;
      //通过@Configuration 标识了一个自定义配置类Datasourceconfig
      @Configuration
      public class Datasourceconfig {
             
          @Bean //通过@Bean注解注入一个DataSource实例对象
          //@ConfigurationProperties(prefix = "spring.datasource")作用:将全局配置文件中以spring.datasource开头的属性值
          // 注入到getDruid()方法并返回的DataSource类对象属性中。这样就可以完成第三方数据源参数值的注入。
          @ConfigurationProperties(prefix = "spring.datasource")
          public DataSource getDruid(){
             
              return new DruidDataSource();
          }
      }
      
    3.2.2 使用注解的方式整合MyBatis

    步骤如下:

  • 在com.itheima下创建包mapper,并在包下创建Mapper***接口文件***CommentMapper.java,内容如下:

    package com.itheima.mapper;
    
    import com.itheima.domain.Comment;
    import org.apache.ibatis.annotations.*;
    
    @Mapper  //表示该类是一个mybatis接口文件,是需要被 springboot进行扫描的。
    public interface CommentMapper {
         
        //查询方法
        @Select("select * from t_Comment where id=#{id}")
        public Comment findById(Integer id);//接口
    
        //添加方法
        @Insert("insert into t_comment values(#{id},#{content},#{author},#{aId})")
        public  void insertComment(Comment comment);
    
        //修改
        @Update("update t_commnet set content=#{content} where id=#{id}")
        public  void updateCommnet(Comment comment);
    
        //删除
        @Delete("delete from t_comment where id=#{id}")
        public  void delectComment(Integer id);
    }
    
  • 编写单元测试进行接口方法测试,这里我们使用Chapter03ApplicationTests,在该测试类中引入CommentMapper接口,并对该接口方法进行测试。内容如下:

    package com.itheima;
    
    import com.itheima.domain.Comment;
    import com.itheima.mapper.CommentMapper;
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest
    class Chapter03ApplicationTests {
         
    
        @Autowired //将CommentMapper接口自动装配为Sping容器的Bean
        private CommentMapper commentMapper;
    
        @Test
        public void contextLoads
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值