mybatisplus入门(代码片段)

Maynor大数据 Maynor大数据     2023-03-03     657

关键词:

MyBatis Plus 概述

1.1 简介

官网:http://mp.baomidou.com/

参考教程:http://mp.baomidou.com/guide/

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 查询
  • 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
  • 内置 Sql 注入剥离器:支持 Sql 注入剥离,有效预防 Sql 注入攻击

2. 入门案例

2.1 搭建环境

  • 步骤一:创建项目:test-mybatis-plus

  • 步骤二:修改pom.xml,添加依赖

  • 步骤三:创建yml文件,配置数据库相关

  • 步骤一:创建项目: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>   
    
    <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>
    
  • 步骤三:创建yml文件,配置数据库相关

    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.D9river
        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 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

  • 步骤2:编写dao

  • 步骤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;

/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
@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 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 updateWrapper)根据 whereEntity 条件,更新记录
int updateById(T entity);根据 ID 修改
  • 查询
方法名描述
T selectById(Serializable id)根据 ID 查询
T selectOne(Wrapper queryWrapper)根据 entity 条件,查询一条记录
List selectBatchIds(Collection idList)根据ID 批量查询
List selectList(Wrapper queryWrapper)根据 entity 条件,查询全部记录
List selectByMap(Map<String, Object> columnMap)根据 columnMap 条件
List<Map<String, Object>> selectMaps(Wrapper queryWrapper)根据 Wrapper 条件,查询全部记录
List selectObjs( Wrapper queryWrapper)根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
IPage selectPage(IPage page, Wrapper queryWrapper)根据 entity 条件,查询全部记录(并翻页)
IPage<Map<String, Object>> selectMapsPage(IPage page, Wrapper queryWrapper)根据 Wrapper 条件,查询全部记录(并翻页)
Integer selectCount(@Param(Constants.WRAPPER) Wrapper queryWrapper)根据 Wrapper 条件,查询总记录数

3.2 添加

    @Test
    public void testInsert() 
        Customer customer = new Customer();
        customer.setCname("测试");

        customerMapper.insert(customer);
    
  • 获得自动增长列信息

    @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);
    

4 查询

4.1 Map条件

    @Test
    public void testMap()
        Map map = new HashMap();
        map.put("cname","测试");
        map.put("password","123456");

        List list = customerMapper.selectByMap(map);
        list.forEach(System.out::println);
    

4.2 QueryWrapper

4.2.1 wrapper介绍

  • Wrapper : 条件构造抽象类,最顶端父类

    • AbstractWrapper : 用于查询条件封装,生成 sql 的 where 条件
      • QueryWrapper : Entity 对象封装操作类,不是用lambda语法
      • UpdateWrapper : Update 条件封装,用于Entity对象更新操作
      • AbstractLambdaWrapper : Lambda 语法使用 Wrapper统一处理解析 lambda 获取 column。
        • LambdaQueryWrapper :看名称也能明白就是用于Lambda语法使用的查询Wrapper
        • LambdaUpdateWrapper : Lambda 更新封装Wrapper
  • 如果想进行复杂条件查询,那么需要使用条件构造器 Wapper,涉及到如下方法

方法名描述
selectOne
selectCount
selectList
selectMaps
selectObjs
update
delete
  • 拼凑条件相关关键字
查询方式说明
setSqlSelect设置 SELECT 查询字段
whereWHERE 语句,拼接 + WHERE 条件
andAND 语句,拼接 + AND 字段=值
andNewAND 语句,拼接 + AND (字段=值)
orOR 语句,拼接 + OR 字段=值
orNewOR 语句,拼接 + OR (字段=值)
eq等于=
allEq基于 map 内容等于=
ne不等于<>
gt大于>
ge大于等于>=
lt小于<
le小于等于<=
like模糊查询 LIKE
notLike模糊查询 NOT LIKE
inIN 查询
notInNOT IN 查询
isNullNULL 值查询
isNotNullIS NOT NULL
groupBy分组 GROUP BY
havingHAVING 关键词
orderBy排序 ORDER BY
orderAscASC 排序 ORDER BY
orderDescDESC 排序 ORDER BY
existsEXISTS 条件语句
notExistsNOT EXISTS 条件语句
betweenBETWEEN 条件语句
notBetweenNOT BETWEEN 条件语句
addFilter自由拼接 SQL
last拼接在最后,例如:last(“LIMIT 1”)

4.2.2 条件查询

  • 基本多条件查询
	@Test
    public void testWrapper()
        // 拼凑条件
        QueryWrapper<Customer> queryWrapper = new QueryWrapper();
        // 1)模糊查询
        queryWrapper.like("cname","测试");
        // 2)等值查询
        queryWrapper.eq("password","777");
        // 3)批量查询
        queryWrapper.in("cid",1,2,3,4);

        // 查询
        List<Customer> list = customerMapper.selectList(queryWrapper);
        list.forEach(System.out::println);
    
  • 条件判断
    @Test
    public void findCondition2() 
        Customer customer = new Customer();
        customer.setPassword("777");
        customer.setCname("888");
        customer.setIdList(Arrays.asList(2,3,4));
        customer.setCid(3);
        //条件查询
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        // 1) 等值查询
        queryWrapper.eq( customer.getPassword()!=null ,"password", customer.getPassword());
        // 2) 模糊查询
        queryWrapper.like(customer.getCname() != null , "cname",customer.getCname());
        // 3) in语句
        queryWrapper.in(customer.getIdList() != null , "cid",customer.getIdList());
        // 4) 大于等于
        queryWrapper.ge(customer.getCid() != null , "cid" , customer.getCid());


        //查询
        List<Customer> list = customerMapper.selectList(queryWrapper);
        //list.forEach(customer-> System.out.println(customer));
        list.forEach(System.out::println);

    

4.3.3 条件更新

  • 基本更新
 	@Test
    public void testWrapperUpdate()
        // 数据
        Customer customer = new Customer();
        customer.setCnamemybatisplus快速入门(2021.07.16)(代码片段)

目录一、MyBatis-Plus入门1、简介2、创建并初始化数据库3、确认idea配置4、创建项目5、编写代码二、主键策略1、插入操作2、MP的主键策略三、自动填充和乐观锁1、更新操作2、自动填充3、乐观锁4、乐观锁实现流程四、查询1、查询... 查看详情

mybatisplus快速入门(2021.07.16)(代码片段)

目录一、MyBatis-Plus入门1、简介2、创建并初始化数据库3、确认idea配置4、创建项目5、编写代码二、主键策略1、插入操作2、MP的主键策略三、自动填充和乐观锁1、更新操作2、自动填充3、乐观锁4、乐观锁实现流程四、查询1、查询... 查看详情

mybatisplus——入门案例(代码片段)

MyBatisPlusMyBatisPlus(简称MP)是基于MyBatis框架基础上开发的增强型工具,旨在简化开发、提高效率开发方式基于MyBatis使用MyBatisPlus基于Spring使用MyBatisPlus基于SpringBoot使用MyBatisPlus SpringBoot整合MyBatis开发过程(复习)创建SpringBoot... 查看详情

mybatisplus入门应用,通用iservice增删改查(代码片段)

先上依赖项目是springboot的,用的maven管理依赖<!--https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter--><dependency><groupId>com.baomidou</groupId><artifactId&g 查看详情

2022年还有人不会用mybatisplus吗?(代码片段)

一、MyBatisPlus入门案例以及简介本文分享MyBatisPlus入门案例与简介,这个和其他课程都不太一样。我们学技术的时候通常是先分享概念,然后是入门案例。对于MyBatisPlus的学习,我们进行了顺序上的调整。主要原因是MyB... 查看详情

java--mybatisplus入门;与mybatis区别;简单使用(代码片段)

阅读前可先参考Java--MyBatis入门_MinggeQingchun的博客-CSDN博客_javamybatis一、MyBatis-PlusMyBatis-Plus(简称MP)是一个 Mybatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生MyBatis-Plus在MyBatis之上... 查看详情

springboot整合mybatisplus(代码片段)

...工具:IDEA基础环境:Maven+JDK8所用技术:SpringBoot、lombok、MybatisPlusSpringBoot版本:2.1.41.3涉及知识点MybatisPlus简介、特性、架构MybatisPlus快速入门MybatisPlus的基本CRUDMybatisPlus的高级查询:like 查看详情

基于mybatisplus完成标准dao的增删改查功能(代码片段)

MyBatisPlus今日目标基于MyBatisPlus完成标准Dao的增删改查功能1,MyBatisPlus入门案例与简介这一节我们来学习下MyBatisPlus的入门案例与简介,这个和其他课程都不太一样,其他的课程都是先介绍概念,然后再写入门案例... 查看详情

mybatisplus快速入门常用设置(表映射主键策略日志)基本使用(代码片段)

(目录)MybatisPlus基础篇1.概述​ MybatisPlus是一款Mybatis增强工具,用于简化开发,提高效率。它在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。​ 官网:https://mp.baomidou.com/2.快速入门2.0准备工作①准备数据CREATETABL... 查看详情

[study]mybatisplus(代码片段)

一、入门案例创建数据库与表CREATEDATABASEmybatis_plus;USEmybatis_plus;CREATETABLE`user`(`id`bigintNOTNULLAUTO_INCREMENT,`name`varchar(255)CHARACTERSETutf8mb4COLLATEutf8mb4_0900_ai_ciNULLDEFA 查看详情

mybatisplus入门(代码片段)

文章目录MyBatisPlus概述1.1简介1.2特点2.入门案例2.1搭建环境2.2数据库和表2.3入门:查询所有3.基本操作3.1常见API3.2添加3.3更新3.4删除4查询4.1Map条件4.2QueryWrapper4.2.1**wrapper介绍**4.2.2条件查询4.3.3条件更新4.3分页4.3.1内置插件4.3.2配... 查看详情

mybatisplus简单使用(代码片段)

一、快速入门导入依赖,具体版本根据自己需要可以选择:<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>LatestVersion</vers 查看详情

mybatisplus快速入门(2021.07.16)(代码片段)

目录一、MyBatis-Plus入门1、简介2、创建并初始化数据库3、确认idea配置4、创建项目5、编写代码二、主键策略1、插入操作2、MP的主键策略三、自动填充和乐观锁1、更新操作2、自动填充3、乐观锁4、乐观锁实现流程四、查询1、查询... 查看详情

2万字总结《mybatisplus—为简化开发而生》(代码片段)

《MybatisPlus—为简化开发而生》文章目录《MybatisPlus—为简化开发而生》1、简介2、特性3、快速入门1、创建数据库`mybatis-plus`2、创建user表3、编写项目,初始化项目,使用SpringBoot初始化4、导入依赖5、连接数据库6、... 查看详情

带你入门mybatisplus

文章目录一、环境搭建1.准备数据库环境2.创建SpringBoot工程二、编写代码1.配置application.yml2.启动类3.添加实体3.添加Mapper三、测试四、自定义文件一、环境搭建1.准备数据库环境创建表:CREATEDATABASE`mybatis_plus`/*!40100DEFAULTC... 查看详情

mybatisplus(代码片段)

文章目录MyBatisPlus简介MyBatisPlus特点##MyBatisPlus结构图MyBatisPlus项目初始化MyBatisPlus安装MyBatisPlus简单示例MyBatisPlus简介MyBatis-Plus(简称MP)是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、... 查看详情

mybatisplus入门程序

参考资料:MybatisPlus官网 环境搭建创建数据库CREATEDATABASE`mybatisplus`?USE`mybatisplus`?CREATETABLE`user`(idBIGINT(20)NOTNULLCOMMENT‘主键ID‘,NAMEVARCHAR(30)NULLDEFAULTNULLCOMMENT‘姓名‘,ageINT(11)NULLDEFAULTNULLCOMM 查看详情

mybatisplus详细教程(代码片段)

目录一、什么是MybatisPlus二、快速入门2.1、创建数据库mybatis_plus2.2、创建user表2.3、插入数据2.4、初始化项目2.5、添加依赖2.6、配置(连接数据库)2.7、编码2.8、开始使用2.9、小结三、配置日志​四、CRUD4.1、插入测试4.2、自定义ID生... 查看详情