MyBatis详细介绍

目录

  • MyBatis详细介绍
    • 什么是ORM
    • Mybatis基本依赖配置
      • Mybatis的依赖配置
      • MySQL的依赖配置
    • 配置连接字符串和MyBatis
      • 配置连接字符串
      • 配置 MyBatis 中的 XML 路径
    • 举个栗子
      • 先来建一个数据库:
      • MyBatis信息配置
      • 添加业务代码
        • 添加 UserMapper.xml
        • 添加实体类
        • 添加 mapper 接口
        • 添加 Service
        • 添加 Controller
    • 查询操作
        • 参数占位符 #{} 和 ${}
        • 注意事项
    • 多表查询
      • 一对一表映射

MyBatis详细介绍

二话不分三次说,先来看图
MyBatis详细介绍

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。Mybatis是ORM框架,能够帮助我们完成面向对象到关系型数据库的映射, 不用写复杂的JDBC 代码以及进行设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(PlainOldJavaObjects,普通老式Java 对象)为数据库中的记录。使用Mybatis框架能否很好的提高我们开发的速度和较少不必要的复杂代码。

不过在此之前我们先来了解一下ORM

什么是ORM

Object-Relationl Mapping,它的作用是在关系型数据库和对象之间作一个映射,这样,我们在具体的操作数据库的时候,就不需要再去和复杂的SQL语句打交道,只要像平时操作对象一样操作它就可以了 。
MyBatis详细介绍

一般的 ORM 框架,会将数据库模型的每张表都映射为一个 Java 类。也就是说使用 MyBatis 可以像操作对象一样来操作数据库中的表,可以实现对象和数据库表之间的转换

Mybatis基本依赖配置

maven项目加入以来即可

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>
    <scope>runtime</scope>
</dependency>

这是在项目开始时创建添加依赖的,难道在过程中如果想添加只能一个一个敲吗?当然不必:
介绍一个插件:
MyBatis详细介绍
这是干啥的呢,就是在过程中添加依赖的:
在pom.xml中右击点击生成:
MyBatis详细介绍
MyBatis详细介绍
MyBatis详细介绍

诺,到了熟悉的界面。。。。

配置连接字符串和MyBatis

配置连接字符串

MyBatis详细介绍
当然贴心的为大家准备好了代码:

datasource:
    url: jdbc:mysql://127.0.0.1:3306/java_gobang?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
    username: root
    password: wjhyd521
    driver-class-name: com.mysql.cj.jdbc.Driver

配置 MyBatis 中的 XML 路径

MyBatis详细介绍

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

举个栗子

先来建一个数据库:

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

-- 使用数据数据
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
);

-- 创建文章表
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
);

-- 创建视频表
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
);

-- 添加一个用户信息
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详细介绍

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

添加业务代码

下面是我们所实现功能的流程:
MyBatis详细介绍

添加 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.model.User">select * from userinfo</select>
</mapper>

添加实体类

package com.example.demo;

import lombok.Data;

import java.util.Date;

@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    private String photo;
    private Date createTime;
    private Date updateTime;
}

添加 mapper 接口

package com.example.demo;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface UserMapper {
    public List<User> getAll();
}

添加 Service

package com.example.demo;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

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

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

添加 Controller

package com.example.demo;

import com.example.demo.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/u")
public class UserController {
    @Resource
    private UserService userService;

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

Mapper、Service、Controller?这命名有没有很熟悉?对开局给大家看的那张图来我们复习一下:

MyBatis详细介绍
是不是豁然开朗

Okk,这下我们用MyBatis实现的用户查询就完成了,测试一下?
怎么测试呢?咱们又没写前端代码?嘿嘿嘿,介绍一款软件:
MyBatis详细介绍
跟一个叫postman的软件功能基本一样,我们来测试一下如下图。
MyBatis详细介绍
至于其他的数据库的增删改我们就不做演示了,毕竟是一样的东西。

查询操作

实现用用户id查询的操作
为啥要查询操作?因为要引出下面的一些东西:

参数占位符 #{} 和 ${}

#{}:预编译处理。
${}:字符直接替换。
预编译处理是指:MyBatis 在处理#{}时,会将 SQL 中的 #{} 替换为?号,使用PreparedStatement 的 set 方法来赋值。直接替换:是MyBatis 在处理 ${} 时,就是把 ${} 替换成变量的值。

看一段栗子:
Controller:
MyBatis详细介绍

@RequestMapping("/getuser")
    public User getUserById(Integer id) {
        return userService.getById(id);
    }

Service:

MyBatis详细介绍

 public User getById(Integer id) {
        return userMapper.getById(id);
    }

UserMapper.xml:

MyBatis详细介绍

<select id="getById" resultType="com.example.demo.model.User">
        select * from userinfo where id=#{id}
    </select>

UserMapper:

MyBatis详细介绍

public User getById(int id);

测试一下:
MyBatis详细介绍

注意事项

1 使用 ${sort} 可以实现排序查询,而使用 #{sort} 就不能实现排序查询了,因为当使用 #{sort} 查询时,如果传递的值为 String 则会加单引号,就会导致 sql 错误。

2 $会有sql注入问题

3 like 使用 #{} 报错,比如:

<select id="findUserByName2" resultType="com.example.demo.model.User"> 
	select * from userinfo where username like '%#{username}%'; 
</select>

相当于: select * from userinfo where username like ‘%‘username’%’;
这个是不能直接使用 ${},可以考虑使用 mysql 的内置函数 concat() 来处理,实现代码如下:

<select id="findUserByName3" resultType="com.example.demo.model.User"> select * from userinfo 	
	where username like concat('%',#{username},'%'); 
</select>

多表查询

这个时候就可以使用 resultMap 了,resultMap 的使用如下:
MyBatis详细介绍

一对一表映射

<resultMap id="BaseMap" type="com.example.demo.model.ArticleInfo">
    <id property="id" column="id"></id>
    <result property="title" column="title"></result>
    <result property="content" column="content"></result>
    <result property="createtime" column="createtime"></result>
    <result property="updatetime" column="updatetime"></result>
    <result property="uid" column="uid"></result>
    <result property="rcount" column="rcount"></result>
    <result property="state" column="state"></result>
    <association property="user" resultMap="com.example.demo.mapper.UserMapper.BaseMap" 
    columnPrefix="u_"></association>
</resultMap>

columnPrefix 如果省略,并且恰好两个表中如果有相同的字段,那么就会导致查询出错,

以上使用 标签,表示一对一的结果映射:

  • property 属性:指定 ArticleInfo 中对应的属性,即用户。
  • resultMap 属性:指定关联的结果集映射,将基于该映射配置来组织用户数据。
  • columnPrefix 属性:绑定一对一对象时,是通过columnPrefix + association.resultMap.column 来映射结果集字段association.resultMap.column是指 标签中
  • resultMap属性,对应的结果集映射中,column字段。
    注意事项:column不能省略

后续闲了将详细更新动态sql

版权声明:程序员胖胖胖虎阿 发表于 2023年9月2日 上午12:32。
转载请注明:MyBatis详细介绍 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...