Spring-Boot整合MyBatis

8次阅读

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

3.1 Spring Boot 整合 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’);

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677

  1. 创建项目,引入相应的启动器
  2. 编写与数据库表 t_comment 和 t_article 对应的实体类 Comment 和 Article

    public class Comment {

private Integer id;

       private String content;

   private String author;

   private Integer aId;

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

       // 省略 toString()方法

}
1234567891011121314151617

public class Article {

private Integer id;

private String title;

private String content;

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

      // 省略 toString()方法

}
12345678910111213141516171819
4. 编写配置文件
(1)在 application.properties 配置文件中进行数据库连接配置

  # MySQL 数据库连接配置

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

  spring.datasource.username=root

  spring.datasource.password=root

123456789
注解方式整合 Mybatis
(1)创建一个用于对数据库表 t_comment 数据操作的接口 CommentMapper

  @Mapper

  public interface CommentMapper {

@Select(“SELECT * FROM t_comment WHERE id =#{id}”)

public Comment findById(Integer id);

  }

123456789101112

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

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

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

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

123456789101112131415
(2)编写测试方法

@RunWith(SpringRunner.class)

@SpringBootTest

class SpringbootPersistenceApplicationTests
{

@Autowired

private CommentMapper commentMapper;

@Test

void contextLoads() {

Comment comment = commentMapper.findById(1);

System.out.println(comment);

}

}
123456789101112131415161718192021222324252627282930313233
打印结果:


控制台中查询的 Comment 的 aId 属性值为 null,没有映射成功。这是因为编写的实体类 Comment 中使用了驼峰命名方式将 t_comment 表中的 a_id 字段设计成了 aId 属性,所以无法正确映射查询结果。
为了解决上述由于驼峰命名方式造成的表字段值无法正确映射到类属性的情况,可以在 Spring
Boot 全局配置文件 application.properties 中添加开启驼峰命名匹配映射配置,示例代码如下

开启驼峰命名匹配映射

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

12345
打印结果:
使用配置文件的方式整合 MyBatis
(1)创建一个用于对数据库表 t_article 数据操作的接口 ArticleMapper

  @Mapper

  public interface ArticleMapper {

public Article selectArticle(Integer id);

}
123456789
(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>
1234567891011121314151617181920212223
(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

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

@Autowired

private ArticleMapper articleMapper;

@Test

public void selectArticle() {

   Article

article = articleMapper.selectArticle(1);

   System.out.println(article);

}
123456789101112131415
打印结果:
3.2
Spring Boot 整合 JPA
(1)添加 Spring Data
JPA 依赖启动器。在项目的 pom.xml 文件中添加 Spring
Data JPA 依赖启动器,示例代码如下

<dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>
12345678
(2)编写 ORM 实体类。

@Entity(name = “t_comment”) // 设置 ORM 实体类,并指定映射的表名

public class Comment {

@Id // 表明映射对应的主键 id

@GeneratedValue(strategy = GenerationType.IDENTITY) // 设置主键自增策略

private Integer id;

private String content;

private String author;

@Column(name = “a_id”)
// 指定映射的表字段名

private Integer aId;

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

     // 省略 toString()方法}

123456789101112131415161718192021222324252627282930313233343536
(3)编写 Repository 接口
:CommentRepository

public interface CommentRepository extends
JpaRepository<Comment,Integer> {

}
1234567
(4)测试

@Autowired

private CommentRepository repository;

@Test

public void selectComment() {

Optional<Comment> optional = repository.findById(1);

          if(optional.isPresent()){

System.out.println(optional.get());

            }

        

System.out.println();

}

12345678910111213141516171819202122232425262728293031
刚学了拉勾教育的《Java 工程师高薪训练营》,看到刚学到的点就回答了。希望拉勾能给我推到想去的公司,目标:字节!!

正文完
 0