【MyBatis-Plus】MyBatis-Plus基本操作快速入门(一)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群版 2核4GB 100GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用版 2核4GB 50GB
简介: 【MyBatis-Plus】MyBatis-Plus基本操作快速入门

1.MyBatis Plus概述

  • Mybatis + 通用Mapper + PageHelper升级成 MyBatis Plus

1.1 简介

官网:MyBatis-Plus

参考教程:简介 | MyBatis-Plus

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

1.2 特点

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer2005、SQLServer 等多种数据库
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 XML 热加载:Mapper 对应的 XML 支持热加载,对于简单的 CRUD 操作,甚至可以无 XML 启动
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 支持关键词自动转义:支持数据库关键词(order、key......)自动转义,还可自定义关键词
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 内置 Sql 注入剥离器:支持 Sql 注入剥离,有效预防 Sql 注入攻击

2.入门案例

2.1 搭建环境

  • 步骤
  • 步骤一:创建项目:test-mybatis-plus
  • 步骤二:修改pom.xml,添加依赖
<dependencies>
        <!-- web 开发 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--MySQL数据库驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--支持lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!--测试-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.0</version>
        </dependency>
    </dependencies>
  • 步骤一:创建项目:test-mybatis-plus
  • 步骤二:修改pom.xml,添加依赖
    <!--确定spring boot的版本-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.5.RELEASE</version>
    </parent>   
  • 步骤三:创建yml文件,配置数据库相关

image.png

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/cloud_db1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 1234
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  #输出日志

2.2 数据库和表

CREATE DATABASE cloud_db1;
USE cloud_db1;
CREATE TABLE `tmp_customer` (
  `cid` INT(11) NOT NULL AUTO_INCREMENT,
  `cname` VARCHAR(50) DEFAULT NULL,
  `password` VARCHAR(32) DEFAULT NULL,
  `telephone` VARCHAR(11) DEFAULT NULL,
  `money` DOUBLE DEFAULT NULL,
  `version` INT(11) DEFAULT NULL,
  `create_time` DATE DEFAULT NULL,
  `update_time` DATE DEFAULT NULL,
  PRIMARY KEY (`cid`)
);
INSERT  INTO `tmp_customer`(`cid`,`cname`,`password`,`telephone`,`money`,`version`,`create_time`,`update_time`) 
VALUES (1,'jack','1234','110',1000,NULL,NULL,NULL),(2,'rose','1234','112',1000,NULL,NULL,NULL),(3,'tom','1234','119',1000,NULL,NULL,NULL);

2.3 入门:查询所有

  • 步骤
  • 步骤1:配置JavaBean,添加MyBatisPlus对应的注解(表、主键、字段等)

           步骤2:编写dao接口,并继承BaseMapper接口

           步骤3:编写启动类

           步骤4:编写测试类

  • 步骤1:配置JavaBean
  • @TableName 表名注解,value属性设置表名
package com.czxy.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.util.List;
@Data
@TableName("tmp_customer")
public class Customer {
    @TableId(type = IdType.AUTO)
    private Integer cid;
    private String cname;
    private String password;
    private String telephone;
    private String money;
    private Integer version;
    @TableField(exist = false)
    private List<Integer> ids;
}
  • 步骤2:编写dao
package com.czxy.mp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.czxy.mp.domain.Customer;
import org.apache.ibatis.annotations.Mapper;
/**
 * Created by liangtong.
 */
@Mapper
public interface CustomerMapper extends BaseMapper<Customer> {
}
  • 步骤3:编写启动类
package com.czxy.mp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * Created by liangtong.
 */
@SpringBootApplication
public class MybatisPlusApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusApplication.class, args);
    }
}
  • 步骤4:编写测试类
package com.czxy;
import com.czxy.mp.MybatisPlusApplication;
import com.czxy.mp.domain.Customer;
import com.czxy.mp.mapper.CustomerMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.List;
/**
 * Created by liangtong.
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MybatisPlusApplication.class)
public class TestDemo01 {
    @Resource
    private CustomerMapper customerMapper;
    @Test
    public void testFindAll() {
        List<Customer> list = customerMapper.selectList(null);
        list.forEach(System.out::println);
    }
}

3.基本操作

3.1 常见API

BaseMapper 封装CRUD操作,泛型 T 为任意实体对象

  • 增删改
方法名 描述
int insert(T entity) 插入一条记录,entity 为 实体对象
int delete(Wrapper<T> wrapper) 根据 entity 条件,删除记录,wrapper 可以为 null
int deleteBatchIds(Collection idList) 根据ID 批量删除
int deleteById(Serializable id) 根据 ID 删除
int deleteByMap(Map<String, Object> map) 根据 columnMap 条件,删除记录
int update(T entity, Wrapper<T> updateWrapper) 根据 whereEntity 条件,更新记录
int updateById(T entity); 根据 ID 修改
  • 查询
方法名 描述
T selectById(Serializable id) 根据 ID 查询
T selectOne(Wrapper<T> queryWrapper) 根据 entity 条件,查询一条记录

List<T> selectBatchIds(Collection idList) 根据ID 批量查询
List<T> selectList(Wrapper<T> queryWrapper) 根据 entity 条件,查询全部记录
List<T> selectByMap(Map<String, Object> columnMap) 根据 columnMap 条件
List<Map<String, Object>> selectMaps(Wrapper<T> queryWrapper) 根据 Wrapper 条件,查询全部记录
List<Object> selectObjs( Wrapper<T> queryWrapper) 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
IPage<T> selectPage(IPage<T> page, Wrapper<T> queryWrapper) 根据 entity 条件,查询全部记录(并翻页)
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, Wrapper<T> queryWrapper) 根据 Wrapper 条件,查询全部记录(并翻页)
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper) 根据 Wrapper 条件,查询总记录数

3.2 添加

@Test
    public void testInsert() {
        Customer customer = new Customer();
        customer.setCname("测试");
        customerMapper.insert(customer);
    }
  • 获得自动增长列信息

image.png

    @Test
    public void testInsert() {
        Customer customer = new Customer();
        customer.setCname("测试");
        customerMapper.insert(customer);
        System.out.println(customer);
    }

3.3 更新

  • 通过id更新
 @Test
    public void testUpdate() {
        Customer customer = new Customer();
        customer.setCid(15);
        customer.setCname("测试777");
        customer.setPassword("777");
        // 需要给Customer设置@TableId
        customerMapper.updateById(customer);
    }
  • 更新所有
  @Test
    public void testUpdate2() {
        Customer customer = new Customer();
        customer.setCname("测试777");
        customer.setPassword("777");
        // 更新所有
        customerMapper.update(customer,null);
    }

3.4 删除

  • 根据id进行删除
@Test
    public void testDelete() {
        // 需要给Customer设置@TableId
        int i = customerMapper.deleteById(11);
        System.out.println(i);
    }
  • 批量删除
    @Test
    public void testBatchDelete() {
        // 需要给Customer设置@TableId
        int i = customerMapper.deleteBatchIds(Arrays.asList(9,10));
        System.out.println(i);
    }
相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
4天前
|
Java 数据库连接 API
后端开发之用Mybatis简化JDBC的开发快速入门2024及数据库连接池技术和lombok工具详解
后端开发之用Mybatis简化JDBC的开发快速入门2024及数据库连接池技术和lombok工具详解
10 3
|
8天前
|
Java 数据库连接 mybatis
在Spring Boot应用中集成MyBatis与MyBatis-Plus
在Spring Boot应用中集成MyBatis与MyBatis-Plus
41 5
|
3天前
|
Java 关系型数据库 MySQL
3.MyBatis和SpringBoot整合及MyBatis-plus与SpringBoot整合
3.MyBatis和SpringBoot整合及MyBatis-plus与SpringBoot整合
11 0
|
9天前
|
Java 数据库连接 Apache
JavaWeb基础第二章(Maven项目与MyBatis 的快速入门与配置)
JavaWeb基础第二章(Maven项目与MyBatis 的快速入门与配置)
|
1月前
|
SQL Java 数据库连接
Mybatis快速入门,Mybatis的核心配置文件
Mybatis快速入门,Mybatis的核心配置文件
28 1
|
1月前
|
SQL Java 数据库连接
Mybatis技术专题(3)MybatisPlus自带强大功能之多租户插件实现原理和实战分析
Mybatis技术专题(3)MybatisPlus自带强大功能之多租户插件实现原理和实战分析
194 1
|
1月前
|
Java 数据库连接 mybatis
shardingsphere集成mybatis/mybatis-plus快速实现简单分片
shardingsphere集成mybatis/mybatis-plus快速实现简单分片
38 0
|
1月前
|
SQL Java 数据库连接
mybatis plus :mybatis简化了jdbc,mybatisplus简化了mybatis
mybatis plus :mybatis简化了jdbc,mybatisplus简化了mybatis
52 0
|
1月前
|
SQL Java 数据库连接
【MyBatisPlus】通俗易懂 快速入门 详细教程
【MyBatisPlus】通俗易懂 快速入门 详细教程
112 0
|
1月前
|
算法 Java 数据库连接
Spring+MySQL+数据结构+集合,Alibaba珍藏版mybatis手写文档
Spring+MySQL+数据结构+集合,Alibaba珍藏版mybatis手写文档