目录
一、MyBatis的概念
二、配置MyBits环境
三、 MyBatis连接数据库查询操作(示例)
创建MySQL数据库表
配置MyBatis
配置连接数据库和MyBatis xml文件
编辑
四、添加业务代码
实体类entity
数据持久层mapper
创建接口类
创建xml文件
服务层Service
控制层controller
一、MyBatis的概念
二、配置MyBits环境
MyBatis的创建是基于SpringBoot项目来创建的,较于SpringBoot项目的创建来说,只是增加了相关的MyBatis 依赖和数据库驱动。
注意:添加MyBatis依赖后,不要忘记添加数据库驱动,因为操作数据库就必须要添加相关数据库的驱动才可实现操作数据库。MyBatis 与数据库驱动成对出现
以操作MySQL数据库为例:
创建MyBatis和SpringBoot类似,在选择相关项目会有所不同,差别如下

 
此时MyBatis项目还需要配置连接数据库的URL,否则项目启动会报错。
步骤:先创建数据库表,再进行MyBatis配置数据库的连接URL
三、 MyBatis连接数据库查询操作(示例)
创建MySQL数据库表
先创建MySQL数据库相关表,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 datetime default now(),
    updatetime datetime default now(),
    `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 datetime default now(),
    updatetime datetime default now(),
    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 datetime default now(),
		updatetime datetime default now(),
  	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); 
 
配置MyBatis
配置连接数据库和MyBatis xml文件
MyBatis 的 XML 中保存是查询数据库的具体操作 SQL,配置如下:
# 开发环境配置文件
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/mycnblog?characterEncoding=utf8&useSSL=false
    username: root
    password: xzf1314520
    driver-class-name: com.mysql.cj.jdbc.Driver
# 配置MyBatis的xml文件
mybatis:
  mapper-locations: classpath:mybatis/*Mapper.xml 
四、添加业务代码
使用MyBatis来操作数据库有以下流程:

创建项目目录如下:


业务代码编写顺序:实体类entity --> 数据持久层 mapper --> 服务层 service --> 控制层 controller
实体类entity
package com.example.demo.entity;
import lombok.Data;
import java.time.LocalDateTime;
@Data // 使用get和set 方法
public class UserInfo {
    private int id;
    private String username;
    private String password;
    private String photo;
    private LocalDateTime createtime;
    private LocalDateTime updatetime;
    private int state;
} 
数据持久层mapper
数据持久层mapper 需要创建接口和xml 文件配置
创建接口类

UserMapper 接口代码如下:
package com.example.demo.mapper;
import com.example.demo.entity.UserInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper // 随着Spring创建而加载
public interface UserMapper {
    UserInfo userId(@Param("id") Integer id);
}
 
创建xml文件

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="userId" resultType="com.example.demo.entity.UserInfo">
        select * from userinfo where id=${id} <!--大括号里面的id 为数据持久层mapper接口方法中 注解param映射的id-->
    </select>
</mapper> 
 
服务层Service
UserService.java
package com.example.demo.service;
import com.example.demo.entity.UserInfo;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
    @Autowired  // 属性注入(将数据持久层 的接口方法注入进行调用)
    private UserMapper userMapper;
    public UserInfo userId(Integer id){ // 此处UserInfo为实体类对象,userId 为数据持久层接口方法
        return userMapper.userId(id); // 返回接口方法中的id
    }
}
 
 
控制层controller
UserController.java
package com.example.demo.controller;
import com.example.demo.entity.UserInfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired // 调用service层的方法
    private UserService userService;
    @RequestMapping("/getid")
    public UserInfo userId(Integer id){ // 使用实体类对象和接口方法
        if(id == null){
            return null;
        }
        return userService.userId(id);
    }
}
 
最后运行启动类,在浏览器输入本地URL,查找id=1的数据库信息

使用MyBatis 查询数据库就建立成功了




















