MyBatis快速入门

目录

一、什么是MyBatis

二、MyBatis的学习要领

三、搭建第一个MyBatis

3.1 创建数据库和表

3.2 添加MyBatis框架支持

3.2.1 老项目添加MyBatis

3.2.2 新项目去添加MyBatis

3.3 设置MyBatis配置信息

3.3.1 设置数据库连接的相关信息

3.3.2 设置MyBatis xml保存路径 和 XML命名规范

3.4 MyBatis模式开发

3.4.1 添加用户实体类

3.4.2 添加Mapper接口

3.4.3 添加UserMapper.xml

3.4.3 Service层

3.4.4 Controller层

3.4.5 使用PostMan进行测试​


一、什么是MyBatis

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

简单来说 MyBatis 是更简单完成程序和数据库交互的⼯具,也就是更简单的操作和读取数据库⼯具。

二、MyBatis的学习要领

MyBatis学习只分为两部分:

  • 配置MyBatis开发环境
  • 使用MyBatis模式和语法操作数据库

三、搭建第一个MyBatis

开始搭建MyBatis之前,我们先来看看MyBatis在整个框架中的定位,框架交互流程图:

我们知道,MyBatis是ORM框架(Object Relational Mapping)即对象关系映射。

在⾯向对象编程语⾔中,将关系型数据库中的数据与对象建⽴起映射关系,进⽽⾃动的完成数据与对象的互相转换:

ORM将数据库映射为对象:

  • 数据库表(table)--> 类(class)
  • 记录(record,⾏数据)--> 对象(object)
  • 字段(field) --> 对象的属性(attribute)

⼀般的 ORM 框架,会将数据库模型的每张表都映射为⼀个 Java 类。

也就是说使⽤ MyBatis 可以像操作对象⼀样来操作数据库中的表,可以实现对象和数据库表之间
的转换,接下来我们来看 MyBatis 的使⽤吧。

3.1 创建数据库和表

接下来我们要实现的功能是:使⽤ MyBatis 的⽅式来读取⽤户表中的所有⽤户,我们使⽤个⼈博
客的数据库和数据包,具体 SQL 如下。

-- 创建数据库
drop database if exists mycnblog;
create database mycnblog DEFAULT CHARACTER SET utf8mb4;

-- 使用数据数据
use mycnblog;

-- 创建表[用户表]
drop table if exists  userinfo;
create table userinfo(
    id int primary key auto_increment,
    username varchar(100) not null,
    password varchar(32) not null,
    photo varchar(500) default '',
    createtime timestamp default current_timestamp,
    updatetime timestamp default current_timestamp,
    `state` int default 1
) default charset 'utf8mb4';

-- 创建文章表
drop table if exists  articleinfo;
create table articleinfo(
    id int primary key auto_increment,
    title varchar(100) not null,
    content text not null,
    createtime timestamp default current_timestamp,
    updatetime timestamp default current_timestamp,
    uid int not null,
    rcount int not null default 1,
    `state` int default 1
)default charset 'utf8mb4';

-- 创建视频表
drop table if exists videoinfo;
create table videoinfo(
  	vid int primary key,
  	`title` varchar(250),
  	`url` varchar(1000),
		createtime timestamp default current_timestamp,
		updatetime timestamp default current_timestamp,
  	uid int
)default charset 'utf8mb4';

-- 添加一个用户信息
INSERT INTO `mycnblog`.`userinfo` (`id`, `username`, `password`, `photo`, `createtime`, `updatetime`, `state`) VALUES 
(1, 'admin', 'admin', '', '2021-12-06 17:10:48', '2021-12-06 17:10:48', 1);

-- 文章添加测试数据
insert into articleinfo(title,content,uid)
    values('Java','Java正文',1);
    
-- 添加视频
insert into videoinfo(vid,title,url,uid) values(1,'java title','http://www.baidu.com',1);

3.2 添加MyBatis框架支持

添加 MyBatis 框架⽀持分为两种情况:⼀种情况是对⾃⼰之前的 Spring 项⽬进⾏升级,另⼀种情况是创建⼀个全新的 MyBatis 和 Spring Boot 的项⽬,下⾯我们分别来演示这两种情况的具体实现。

3.2.1 老项目添加MyBatis

如果是在老项目中添加新增功能,添加框架支持:

<!-- 添加 MyBatis 框架 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>
<!-- 添加 MySQL 驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
    <scope>runtime</scope>
</dependency>

添加了 MyBatis 之后,为什么还需要添加 MySQL 驱动呢?

因为MyBatis 就像⼀个平台(类似淘宝),⽽数据库相当于商家有很多种,不⽌有 MySQL,还有 SQLServer、 MariaDB等等,就像叫人买东西一样,不能告诉只告诉别人买这个东西,需要告诉别人具体到哪个地方去买。

3.2.2 新项目去添加MyBatis

完成了框架和驱动的安装,运行程序时,你会发现程序报错了。

这是因为你只告诉了程序要连接Mysql而没有告诉程序Mysql的具体信息,比如存储位置,密码等。这就好比你叫张三去找李四,可是李四到底在哪呢?如果没有人告知,程序是无法判断的。

3.3 设置MyBatis配置信息

此步骤需要进行两项配置,数据库连接字符串设置和MyBatis的XML文件配置。

3.3.1 设置数据库连接的相关信息

如果是application.properties 添加如下内容;

spring.datasource.url=jdbc:mysql://localhost:3306/mycnblog?characterEncoding=utf8&useSSL=false
spring.datasource.username=root

spring.datasource.password=030106
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#设置MyBatis
mybatis.mapper-locations=classpath:mapper/*Mapper.xml

需要注意的是:

如果使⽤ mysql-connector-java 是 5.x 之前的使⽤的是“com.mysql.jdbc.Driver”,如果是⼤于 5.x
使⽤的是“com.mysql.cj.jdbc.Driver”。

3.3.2 设置MyBatis xml保存路径 和 XML命名规范

#设置MyBatis
mybatis.mapper-locations=classpath:mapper/*Mapper.xml

分析:classpath代表的是当前项目的根路径,mapper代表的是所有关于MyBatis的配置文件会放在这里,*Mapper.xml代表的是所有与MyBatis相关的xml文件都命名为某某某Mapper,xml。

3.4 MyBatis模式开发

主要是由两部分组成:

  • interface:让其他层可以注入使用的接口
  • mybatis:xml -> 具体实现sql (可以理解为是上面interface的实现)

接口和XML文件的关系

  • 通过接口和 XML 文件的映射关系,实现了接口中的方法与 XML 文件中的 SQL 语句的绑定。
  • 当调用接口的方法时,MyBatis会根据方法的名称和参数类型找到对应的XML文件中的SQL语句,并执行该SQL语句。
  • XML文件中的SQL语句可以直接调用数据库操作,也可以通过映射配置将结果集映射到对象中。

为什么MyBatis要这么麻烦的定义一个接口和一个xml文件才能实现执行sql的功能呢?

:因为实际开发的过程中,SQL语句往往是比较复杂的,如果写在Java的类中不太合适的,因此采用了接口+XML文件的形式。

下面按照开发的工程思路,也就是下面的流程来实现MyBatis查询用户的功能:

 实现interface和xml文件时候需要注意格式要与配置文件下所书写的格式相同:

 3.4.1 添加用户实体类

package com.example.demo.entity;

import lombok.Data;

import java.time.LocalDateTime;


@Data
public class UserEntity {
    private Integer id;
    private String username;
    private String password;
    private String photo;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
    private Integer state;
}

需要注意:这里的属性名最好与字段名保持一致,因为这样MyBatis可以自动实现关系的映射。

 3.4.2 添加Mapper接口

在添加该接口之前,我们先来认识一下@Mapper注解:     

: @Mapper用于标识一个接口或类是MyBatis的映射器,  并将其注册为String的Bean,这样就可以在使用这个映射器的地方,可以通过依赖注入的方式直接使用它,而无需手动创建实例。

package com.example.demo.mapper;

import com.example.demo.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper//不能忽略
public interface UserMapper {
    List<UserEntity> getAll();
}

3.4.3 添加UserMapper.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.example.demo.mapper.UserMapper">
    <select id="getAll" resultType="com.example.demo.entity.UserEntity">
        select * from userinfo
    </select>
</mapper>

 需要注意的是namespace所写的接口需要与实际实现的接口保持一致:

 UserMapper.xml 查询所有用户的具体实现SQL:

<?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.example.demo.mapper.UserMapper">
    <select id="getAll" resultType="com.example.demo.entity.UserEntity">
        select * from userinfo
    </select>
</mapper>

  需要这里这里id与resultType要与接口中的方法相等。

 以下是对以上标签的说明:

  • <mapper>标签:需要指定 namespace 属性,表示命名空间,其值为 mapper 接⼝的全限定名,包括全包名.类名。
  • <select>查询标签:是⽤来执⾏数据库的查询操作的。其中的id:是和 Interface(接⼝)中定义的⽅法名称⼀样的,表示对接⼝的具体实现⽅法。而resultType:是返回的数据类型,也就是开头我们定义的实体类。

按照标准的分层结构,需要Controller层和Service层,因此我们需要完成Service层和Controller层的编写。

3.4.3 Service层

服务层的代码如下:

package com.example.demo.service;

import com.example.demo.entity.UserEntity;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<UserEntity> getAll() {
        return userMapper.getAll();
    }
}

可能有人会好奇:明明UserMapper是一个接口,@Autowired为什么可以让接口注入到当前对象中?

当我们在类中使用@Autowired注解注入 MyBatis 的接口时,实际上注入的是 MyBatis 自动生成的代理对象。这个代理对象实现了接口定义的方法,并能够与数据库进行交互。

3.4.4 Controller层

package com.example.demo.controller;

import com.example.demo.entity.UserEntity;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/getAll")
    public List<UserEntity> getAll() {
        return userService.getAll();
    }

}

3.4.5 使用PostMan进行测试

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值