Mybatis 入门篇(含实战)

238 阅读4分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第2天,点击查看活动详情

前言

Mybatis 可以说是国内使用频率最高的 ORM 框架,作为一个立志搭建 Java 全知识体系的男人,对 Mybais 的研究怎么能不深入呢,于是我就开了一个新的系列,「Mybatis 系列」

本文的主要内容是 Mybatis 的基础部分,包括

  • Mybatis 的基础概念
  • Mybatis 集成 SpringBoot 入门实战

读完本文的目标是

  • 了解 Mybatis 的基础概念
  • 从零到一搭建 Mybatis 项目,可以做到增删查改

Mybatis 简介

以下文字采自 Mybatis 官网mybatis.org/mybatis-3/z…

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

更贴切一点的说法是,Mybatis 是一款半自动的 ORM(Object Relational Mapping) 框架,为什么说它是半自动呢?

对于像 Hibernate 这样的全自动 ORM 框架来说,,在查询的数据的时候可以根据对象关系模型 POJO 直接与数据库的字段进行映射;而 Mybatis 不一样,Mybatis 在查询关联对象时,需要通过手动编写 SQL 来完成,所以称 Mybatis 是半自动的 ORM 框架

一些优点

  • 简单易学:Mybatis 本身就很轻巧,源码也不算复杂,通过文档和源代码,可以比较完全的掌握 Mybatis
  • 灵活:Mybatis 的公认的最大特性就是灵活;Mybatis 通过 XML 文件来统一管理 SQL,基于 XML 和各种标签来实现动态 SQL,对于很多的 SQL 优化,复杂查询来说,Mybatis 可以称得上是真香了
  • SQL 与代码分离:提高了可维护性

一些缺点

  • 编写SQL语句时工作量很大,尤其是字段多、关联表多时,为了解决这个问题,引入了 Mybatis Plus、代码生成工具等来解决增删查改代码的重复编写
  • SQL语句依赖于数据库,导致数据库移植性差,不能更换数据库;像 JPA 来说,只需要简单的更换配置文件就可以了切换数据库
  • 二级缓存机制不佳,基本没人用

Mybatis Plus

官网:baomidou.com/

image.png

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生

Mybatis 的 Logo 是一只红鸟,而 Mybatis Plus 的 Logo 则是一只蓝鸟,就像魂斗罗中的红蓝双雄一样

引入了 Mybatis Plus 的项目,只需要简单的配置,启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作,就像在使用 JPA 一样丝滑

Mybatis 入门实战

使用 SpringBoot 集成 Mybatis,对 MySQL 中的数据做一个增删查改

使用

  • SpringBoot 2.5.1
  • SpringBoot Mybatis 2.1.4
  • MySQL 5.7
  • JDK 1.8

表结构准备

创建一个学生表,用来测试 Demo

CREATE TABLE student(
    `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
    `name` VARCHAR(50) NOT NULL COMMENT '姓名',
    `age`  int(11) NOT NULL COMMENT '年龄',
    PRIMARY KEY (`id`)
);

依赖引入

Pom.xml

<!-- SpringBoot 依赖配置 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>2.5.1</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.5.1</version>
</dependency>

<!-- Mybatis 依赖配置 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>

最简代码编写

本示例贴出了使用 Mybatis 的最简代码

首先在 IDEA 里面添加数据源

image.png

实际代码

对于 CRUD 的代码,有很多工具可以完成代码的自动生成;比如 IDEA 的插件 EasyCode ,内置了 Mybatis 和 Mybatis-Plus 的模板,妈妈再也不用担心我天天写 CRUD;当然同类的解决方案也是有的,比如 Mybatis Generator,稍微复杂一点的需求建议可以看看若依后端管理系统,作者基于 Mybatis Generator 封装了一个独立的代码生成模块

建立实体类 StudentEntity

public class Student {
    private Long id;
  
    private String name;
  
    private Integer age;
  
    /** 省略 Get/Set */
}

建立 Mapper,这里将它命名为 Dao;建立一个查询,一个新增的方法,Dao 直接和数据库交互

public interface StudentDao {
    Student queryById(Long id);

    int insert(Student student);
}

建立 Controller,直接跳过 Service 进行查询和插入的测试

@RestController
@RequestMapping("student")
public class StudentController {
    @Resource
    private StudentDao studentDao;

    @GetMapping("{id}")
    public ResponseEntity<Student> queryById(@PathVariable("id") Long id) {
        return ResponseEntity.ok(this.studentDao.queryById(id));
    }

    @PostMapping
    public ResponseEntity<Student> add(@RequestBody Student student) {
        this.studentDao.insert(student);
        return ResponseEntity.ok(student);
    }
}

建立 StudentDao.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="cn.wzed.mybatisdemo.dao.StudentDao">

    <resultMap type="cn.wzed.mybatisdemo.entity.Student" id="StudentMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="age" column="age" jdbcType="INTEGER"/>
    </resultMap>

    <!--查询单个-->
    <select id="queryById" resultMap="StudentMap">
        select id,
               name,
               age
        from student
        where id = #{id}
    </select>

       <!--新增所有列-->
    <insert id="insert" keyProperty="id" useGeneratedKeys="true">
        insert into student(name, age)
        values (#{name}, #{age})
    </insert>
</mapper>

项目配置

现在的项目还不能跑,因为还缺少一些必要的配置为了不在每个 Dao 类上写注解 @Mapper,可以直接配置 Mybatis 去扫描存放 Dao 接口的包

添加 Mybatis 配置类 MybatisConfig

@Configuration
@MapperScan("cn.wzed.mybatisdemo.dao")
public class MybatisConfig {
}

application.yml 文件中,配置数据源,以及 mapper.xml 的存放位置

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

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo
    username: root
    password: 123456

启动项目,调用接口,就可以测试成功啦!