SpringBoot基础回顾10

6次阅读

共计 4714 个字符,预计需要花费 12 分钟才能阅读完成。

3. SpringBoot 数据访问

SpringData 是 Spring 提供的一个用于简化数据库访问、支持云服务的开源框架。它是一个伞形项目,包含了大量关系型数据库及非关系型数据库的数据访问解决方案,其设计目的是使我们可以快速且简单地使用各种数据访问技术。Spring Boot 默认采用整合 SpringData 的方式统一处理数据访问层,通过添加大量自动配置,引入各种数据访问模板 xxxTemplate 以及统一的 Repository 接口,从而达到简化数据访问层的操作。

Spring Data 提供了多种类型数据库支持,对支持的的数据库进行了整合管理,提供了各种依赖启动器,接下来,通过一张表罗列提供的常见数据库依赖启动器,如表所示。

| 名称 | 描述
|

| 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 键值数据存储与 Spring Data Redis 和 Jedis 客户端 |


除此之外,还有一些框架技术,Spring Data 项目并没有进行统一管理,Spring Boot 官方也没有提供对应的依赖启动器,但是为了迎合市场开发需求、这些框架技术开发团队自己适配了对应的依赖启动器,例如,mybatis-spring-boot-starter 支持 MyBatis 的使用

3.1 Spring Boot 整合 MyBatis


MyBatis 是一款优秀的持久层框架,Spring Boot 官方虽然没有对 MyBatis 进行整合,但是 MyBatis 团队自行适配了对应的启动器,进一步简化了使用 MyBatis 进行数据的操作


因为 Spring Boot 框架开发的便利性,所以实现 Spring Boot 与数据访问层框架(例如 MyBatis)的整合非常简单,主要是引入对应的依赖启动器,并进行数据库相关参数设置即可

基础环境搭建

1. 数据准备


在 MySQL 中,先创建了一个数据库 springbootdata,然后创建了两个表 t_article 和 t_comment 并向表中插入数据。其中评论表 t_comment 的 a_id 与文章表 t_article 的主键 id 相关联


       #
创建数据库

       CREATE
DATABASE springbootdata;

       #
选择使用数据库

      USE springbootdata;

       #
创建表 t_article 并插入相关数据

       DROP
TABLE IF EXISTS 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;

       INSERT
INTO t_article VALUES ('1', 'Spring Boot 基础入门', '从入门到精通讲解...');

       INSERT
INTO t_article VALUES ('2', 'Spring Cloud 基础入门', '从入门到精通讲解...');

      # 创建表 t_comment 并插入相关数据

       DROP
TABLE IF EXISTS 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;

       INSERT
INTO t_comment VALUES ('1', '很全、很详细', 'luccy', '1');

       INSERT
INTO t_comment VALUES ('2', '赞一个', 'tom', '1');

       INSERT
INTO t_comment VALUES ('3', '很详细', 'eric', '1');

       INSERT
INTO t_comment VALUES ('4', '很好,非常详细', '张三', '1');

       INSERT
INTO t_comment VALUES ('5', '很不错', '李四', '2');

 

2. 创建项目,引入相应的启动器

<img
src=”./images/image-20191227142727497.png”
alt=”image-20191227142727497″ style=”zoom:67%;” />

3. 编写与数据库表 t_comment 和 t_article 对应的实体类 Comment 和 Article


      public class Comment {

             
private Integer id;

           private String content;

       private String author;

       private Integer aId;

           // 省略属性 getXX() 和 setXX() 方法

           // 省略 toString() 方法}

public class Article {

 

   
private Integer id;

   
private String title;

   
private String content;

              // 省略属性 getXX() 和 setXX() 方法

          // 省略 toString() 方法}

4. 编写配置文件

(1)在 application.properties 配置文件中进行数据库连接配置


      # MySQL 数据库连接配置

      spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC

      spring.datasource.username=root

      spring.datasource.password=root

注解方式整合 Mybatis

(1)创建一个用于对数据库表 t_comment 数据操作的接口 CommentMapper


      @Mapper

      public interface CommentMapper {@Select("SELECT * FROM t_comment WHERE id =#{id}")

         
public Comment findById(Integer id);

      }

@Mapper 注解表示该类是一个 MyBatis 接口文件,并保证能够被 Spring Boot 自动扫描到 Spring 容器中 

 

对应的接口类上添加了 @Mapper 注解,如果编写的 Mapper 接口过多时,需要重复为每一个接口文件添加 @Mapper 注解

 

为了解决这种麻烦,可以直接在 Spring Boot 项目启动类上添加 @MapperScan("xxx") 注解,不需要再逐个添加

 

@Mapper 注解,@MapperScan("xxx") 注解的作用和 @Mapper 注解类似,但是它必须指定需要扫描的具体包名

(2)编写测试方法


@RunWith(SpringRunner.class)

@SpringBootTest

class SpringbootPersistenceApplicationTests
{

 

   
@Autowired

   
private CommentMapper commentMapper;

 

   
@Test

   
void contextLoads() {Comment comment = commentMapper.findById(1);

       
System.out.println(comment);

    }

}

打印结果:

<img src=”./images/image-20191227153811292.png”
alt=”image-20191227153811292″ style=”zoom:67%;” />


控制台中查询的 Comment 的 aId 属性值为 null,没有映射成功。这是因为编写的实体类 Comment 中使用了驼峰命名方式将 t_comment 表中的 a_id 字段设计成了 aId 属性,所以无法正确映射查询结果。

为了解决上述由于驼峰命名方式造成的表字段值无法正确映射到类属性的情况,可以在 Spring
Boot 全局配置文件 application.properties 中添加开启驼峰命名匹配映射配置,示例代码如下


#开启驼峰命名匹配映射

mybatis.configuration.map-underscore-to-camel-case=true

打印结果:

​ <img src=”./images/image-20191227154947834.png”
alt=”image-20191227154947834″ style=”zoom:67%;” />

使用配置文件的方式整合 MyBatis

(1)创建一个用于对数据库表 t_article 数据操作的接口 ArticleMapper


      @Mapper

      public interface ArticleMapper {public Article selectArticle(Integer id);

}

(2)创建 XML 映射文件


resources 目录下创建一个统一管理映射文件的包 mapper,并在该包下编写与 ArticleMapper 接口方应的映射文件 ArticleMapper.xml


<?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.lagou.mapper.ArticleMapper">

   
<select id="selectArticle"
resultType="Article">

       
select * from Article

   
</select>

</mapper>

(3)配置 XML 映射文件路径。在项目中编写的 XML 映射文件,Spring Boot 并无从知晓,所以无法扫描到该自定义编写的 XML 配置文件,还必须在全局配置文件 application.properties 中添加 MyBatis 映射文件路径的配置,同时需要添加实体类别名映射路径,示例代码如下


#配置 MyBatis 的 xml 配置文件路径

mybatis.mapper-locations=classpath:mapper/*.xml

#配置 XML 映射文件中指定的实体类别名路径

mybatis.type-aliases-package=com.lagou.pojo

(4)编写单元测试进行接口方法测试


@Autowired

private ArticleMapper articleMapper;

@Test

public void selectArticle() {

       Article
article = articleMapper.selectArticle(1);

       System.out.println(article);

}

上了拉勾教育的《Java 工程师高薪训练营》,做一下笔记。希望拉勾能给我推到想去的公司,目标:字节!!

正文完
 0