MyBatis Plus快速入门

2023-05-16

MyBatis Plus

国产的开源框架,基于 MyBatis

核心功能就是简化 MyBatis 的开发,提高效率。

MyBatis Plus 快速上手

Spring Boot(2.3.0) + MyBatis Plus(国产的开源框架,并没有接入到 Spring 官方孵化器中)

1、创建 Maven 工程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Jid3mHQ5-1644197491781)(/Users/southwind/Library/Application Support/typora-user-images/image-20200516201427232.png)]

2、pom.xml 引入 MyBatis Plus 的依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.3.1.tmp</version>
</dependency>

3、创建实体类

package com.southwind.mybatisplus.entity;

import lombok.Data;

@Data
public class User {
    private Integer id;
    private String name;
    private Integer age;
}

4、创建 Mapper 接口

package com.southwind.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.southwind.mybatisplus.entity.User;

public interface UserMapper extends BaseMapper<User> {

}

5、application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: root
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

6、启动类需要添加 @MapperScan(“mapper所在的包”),否则无法加载 Mppaer bean。

package com.southwind.mybatisplus;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.southwind.mybatisplus.mapper")
public class MybatisplusApplication {

    public static void main(String[] args) {
        SpringApplication.run(MybatisplusApplication.class, args);
    }

}

7、测试

package com.southwind.mybatisplus.mapper;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class UserMapperTest {

    @Autowired
    private UserMapper mapper;

    @Test
    void test(){
        mapper.selectList(null).forEach(System.out::println);
    }

}

常用注解

@TableName

映射数据库的表名

package com.southwind.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName(value = "user")
public class Account {
    private Integer id;
    private String name;
    private Integer age;
}

@TableId

设置主键映射,value 映射主键字段名

type 设置主键类型,主键的生成策略,

AUTO(0),
NONE(1),
INPUT(2),
ASSIGN_ID(3),
ASSIGN_UUID(4),
/** @deprecated */
@Deprecated
ID_WORKER(3),
/** @deprecated */
@Deprecated
ID_WORKER_STR(3),
/** @deprecated */
@Deprecated
UUID(4);
描述
AUTO数据库自增
NONEMP set 主键,雪花算法实现
INPUT需要开发者手动赋值
ASSIGN_IDMP 分配 ID,Long、Integer、String
ASSIGN_UUID分配 UUID,Strinig

INPUT 如果开发者没有手动赋值,则数据库通过自增的方式给主键赋值,如果开发者手动赋值,则存入该值。

AUTO 默认就是数据库自增,开发者无需赋值。

ASSIGN_ID MP 自动赋值,雪花算法。

ASSIGN_UUID 主键的数据类型必须是 String,自动生成 UUID 进行赋值

@TableField

映射非主键字段,value 映射字段名

exist 表示是否为数据库字段 false,如果实体类中的成员变量在数据库中没有对应的字段,则可以使用 exist,VO、DTO

select 表示是否查询该字段

fill 表示是否自动填充,将对象存入数据库的时候,由 MyBatis Plus 自动给某些字段赋值,create_time、update_time

1、给表添加 create_time、update_time 字段

2、实体类中添加成员变量

package com.southwind.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.FieldFill;import com.baomidou.mybatisplus.annotation.TableField;import com.baomidou.mybatisplus.annotation.TableId;import com.baomidou.mybatisplus.annotation.TableName;import lombok.Data;import java.util.Date;@Data@TableName(value = "user")public class User {    @TableId    private String id;    @TableField(value = "name",select = false)    private String title;    private Integer age;    @TableField(exist = false)    private String gender;    @TableField(fill = FieldFill.INSERT)    private Date createTime;    @TableField(fill = FieldFill.INSERT_UPDATE)    private Date updateTime;}

3、创建自动填充处理器

package com.southwind.mybatisplus.handler;import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;import org.apache.ibatis.reflection.MetaObject;import org.springframework.stereotype.Component;import java.util.Date;@Componentpublic class MyMetaObjectHandler implements MetaObjectHandler {    @Override    public void insertFill(MetaObject metaObject) {        this.setFieldValByName("createTime",new Date(),metaObject);        this.setFieldValByName("updateTime",new Date(),metaObject);    }    @Override    public void updateFill(MetaObject metaObject) {        this.setFieldValByName("updateTime",new Date(),metaObject);    }}

@Version

标记乐观锁,通过 version 字段来保证数据的安全性,当修改数据的时候,会以 version 作为条件,当条件成立的时候才会修改成功。

version = 2

线程 1:update … set version = 2 where version = 1

线程2 :update … set version = 2 where version = 1

1、数据库表添加 version 字段,默认值为 1

2、实体类添加 version 成员变量,并且添加 @Version

package com.southwind.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.*;import lombok.Data;import java.util.Date;@Data@TableName(value = "user")public class User {    @TableId    private String id;    @TableField(value = "name",select = false)    private String title;    private Integer age;    @TableField(exist = false)    private String gender;    @TableField(fill = FieldFill.INSERT)    private Date createTime;    @TableField(fill = FieldFill.INSERT_UPDATE)    private Date updateTime;    @Version    private Integer version;}

3、注册配置类

package com.southwind.mybatisplus.config;import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class MyBatisPlusConfig {        @Bean    public OptimisticLockerInterceptor optimisticLockerInterceptor(){        return new OptimisticLockerInterceptor();    }    }

@EnumValue

1、通用枚举类注解,将数据库字段映射成实体类的枚举类型成员变量

package com.southwind.mybatisplus.enums;import com.baomidou.mybatisplus.annotation.EnumValue;public enum StatusEnum {    WORK(1,"上班"),    REST(0,"休息");    StatusEnum(Integer code, String msg) {        this.code = code;        this.msg = msg;    }    @EnumValue    private Integer code;    private String msg;}
package com.southwind.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.*;import com.southwind.mybatisplus.enums.StatusEnum;import lombok.Data;import java.util.Date;@Data@TableName(value = "user")public class User {    @TableId    private String id;    @TableField(value = "name",select = false)    private String title;    private Integer age;    @TableField(exist = false)    private String gender;    @TableField(fill = FieldFill.INSERT)    private Date createTime;    @TableField(fill = FieldFill.INSERT_UPDATE)    private Date updateTime;    @Version    private Integer version;    private StatusEnum status;}

application.yml

type-enums-package:   com.southwind.mybatisplus.enums

2、实现接口

package com.southwind.mybatisplus.enums;import com.baomidou.mybatisplus.core.enums.IEnum;public enum AgeEnum implements IEnum<Integer> {    ONE(1,"一岁"),    TWO(2,"两岁"),    THREE(3,"三岁");    private Integer code;    private String msg;    AgeEnum(Integer code, String msg) {        this.code = code;        this.msg = msg;    }    @Override    public Integer getValue() {        return this.code;    }}

@TableLogic

映射逻辑删除

1、数据表添加 deleted 字段

2、实体类添加注解

package com.southwind.mybatisplus.entity;import com.baomidou.mybatisplus.annotation.*;import com.southwind.mybatisplus.enums.AgeEnum;import com.southwind.mybatisplus.enums.StatusEnum;import lombok.Data;import java.util.Date;@Data@TableName(value = "user")public class User {    @TableId    private String id;    @TableField(value = "name",select = false)    private String title;    private AgeEnum age;    @TableField(exist = false)    private String gender;    @TableField(fill = FieldFill.INSERT)    private Date createTime;    @TableField(fill = FieldFill.INSERT_UPDATE)    private Date updateTime;    @Version    private Integer version;    @TableField(value = "status")    private StatusEnum statusEnum;    @TableLogic    private Integer deleted;}

3、application.yml 添加配置

global-config:  db-config:    logic-not-delete-value: 0    logic-delete-value: 1

查询

//mapper.selectList(null);QueryWrapper wrapper = new QueryWrapper();//        Map<String,Object> map = new HashMap<>();//        map.put("name","小红");//        map.put("age",3);//        wrapper.allEq(map);//        wrapper.gt("age",2);//        wrapper.ne("name","小红");//        wrapper.ge("age",2);//like '%小'//        wrapper.likeLeft("name","小");//like '小%'//        wrapper.likeRight("name","小");//inSQL//        wrapper.inSql("id","select id from user where id < 10");//        wrapper.inSql("age","select age from user where age > 3");//        wrapper.orderByDesc("age");//        wrapper.orderByAsc("age");//        wrapper.having("id > 8");mapper.selectList(wrapper).forEach(System.out::println);
//        System.out.println(mapper.selectById(7));//        mapper.selectBatchIds(Arrays.asList(7,8,9)).forEach(System.out::println);//Map 只能做等值判断,逻辑判断需要使用 Wrapper 来处理//        Map<String,Object> map = new HashMap<>();//        map.put("id",7);//        mapper.selectByMap(map).forEach(System.out::println);QueryWrapper wrapper = new QueryWrapper();wrapper.eq("id",7);        System.out.println(mapper.selectCount(wrapper));        //将查询的结果集封装到Map中//        mapper.selectMaps(wrapper).forEach(System.out::println);//        System.out.println("-------------------");//        mapper.selectList(wrapper).forEach(System.out::println);//分页查询//        Page<User> page = new Page<>(2,2);//        Page<User> result = mapper.selectPage(page,null);//        System.out.println(result.getSize());//        System.out.println(result.getTotal());//        result.getRecords().forEach(System.out::println);//        Page<Map<String,Object>> page = new Page<>(1,2);//        mapper.selectMapsPage(page,null).getRecords().forEach(System.out::println);//        mapper.selectObjs(null).forEach(System.out::println);System.out.println(mapper.selectOne(wrapper));

自定义 SQL(多表关联查询)

package com.southwind.mybatisplus.entity;import lombok.Data;@Datapublic class ProductVO {    private Integer category;    private Integer count;    private String description;    private Integer userId;    private String userName;}
package com.southwind.mybatisplus.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.southwind.mybatisplus.entity.ProductVO;import com.southwind.mybatisplus.entity.User;import org.apache.ibatis.annotations.Select;import java.util.List;public interface UserMapper extends BaseMapper<User> {    @Select("select p.*,u.name userName from product p,user u where p.user_id = u.id and u.id = #{id}")    List<ProductVO> productList(Integer id);}

添加

User user = new User();user.setTitle("小明");user.setAge(22);mapper.insert(user);System.out.println(user);

删除

//mapper.deleteById(1);//        mapper.deleteBatchIds(Arrays.asList(7,8));//        QueryWrapper wrapper = new QueryWrapper();//        wrapper.eq("age",14);//        mapper.delete(wrapper);Map<String,Object> map = new HashMap<>();map.put("id",10);mapper.deleteByMap(map);

修改

//        //update ... version = 3 where version = 2//        User user = mapper.selectById(7);//        user.setTitle("一号");        //update ... version = 3 where version = 2//        User user1 = mapper.selectById(7);//        user1.setTitle("二号");        mapper.updateById(user1);//        mapper.updateById(user);User user = mapper.selectById(1);user.setTitle("小红");QueryWrapper wrapper = new QueryWrapper();wrapper.eq("age",22);mapper.update(user,wrapper);

分页

  1. 配置
@Configurationpublic class MybatisPlusConfig {    @Bean    public MybatisPlusInterceptor mybatisPlusInterceptor() {        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));        return interceptor;    }}
  1. dao层

    @Select("${uid}")//这里传入了page 自动分页IPage<TableAudioName> findYouLike(Page<TableAudioName> page, String uid);
    

    page参数详解(源码)

    /** * 查询数据列表 */protected List<T> records = Collections.emptyList();/** * 总数 */protected long total = 0;/** * 每页显示条数,默认 10 */protected long size = 10;/** * 当前页 */protected long current = 1;
    

    ps:

    比如我要查limit 0,3 3,3

    page.setSize(3)

    page.setcurrent(“当前是该第几页了”) // 比如 1 为0,3

缓存

//使用注解方式开启二级缓存

在dao上加注解

@CacheNamespace(blocking = true)
public interface TestDao extends BaseMapper<Test> {		@Select("SELECT * from test,test2 where test.id = test2.f_id and test.id = #{id}")		//不使用缓存    	@Options(useCache = false)    	Test getById(String id);	//默认使用缓存	@Select("select * from test where id = #{id}")	Test getById(List<String> ids);}

MyBatisPlus 自动生成

根据数据表自动生成实体类、Mapper、Service、ServiceImpl、Controller

1、pom.xml 导入 MyBatis Plus Generator

<dependency>    <groupId>com.baomidou</groupId>    <artifactId>mybatis-plus-generator</artifactId>    <version>3.3.1.tmp</version></dependency><dependency>    <groupId>org.apache.velocity</groupId>    <artifactId>velocity</artifactId>    <version>1.7</version></dependency>

Velocity(默认)、Freemarker、Beetl

2、启动类

package com.southwind.mybatisplus;import com.baomidou.mybatisplus.annotation.DbType;import com.baomidou.mybatisplus.generator.AutoGenerator;import com.baomidou.mybatisplus.generator.config.DataSourceConfig;import com.baomidou.mybatisplus.generator.config.GlobalConfig;import com.baomidou.mybatisplus.generator.config.PackageConfig;import com.baomidou.mybatisplus.generator.config.StrategyConfig;import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;public class Main {    public static void main(String[] args) {        //创建generator对象        AutoGenerator autoGenerator = new AutoGenerator();        //数据源        DataSourceConfig dataSourceConfig = new DataSourceConfig();        dataSourceConfig.setDbType(DbType.MYSQL);        dataSourceConfig.setUrl("jdbc:mysql://ip:3306/db?useUnicode=true&characterEncoding=UTF-8");        dataSourceConfig.setUsername("root");        dataSourceConfig.setPassword("root");        dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");        autoGenerator.setDataSource(dataSourceConfig);        //全局配置        GlobalConfig globalConfig = new GlobalConfig();        globalConfig.setOutputDir(System.getProperty("user.dir")+"/src/main/java");        globalConfig.setOpen(false);        globalConfig.setAuthor("southwind");        globalConfig.setServiceName("%sService");        autoGenerator.setGlobalConfig(globalConfig);        //包信息        PackageConfig packageConfig = new PackageConfig();        packageConfig.setParent("com.southwind.mybatisplus");        packageConfig.setModuleName("generator");        packageConfig.setController("controller");        packageConfig.setService("service");        packageConfig.setServiceImpl("service.impl");        packageConfig.setMapper("mapper");        packageConfig.setEntity("entity");        autoGenerator.setPackageInfo(packageConfig);        //配置策略        StrategyConfig strategyConfig = new StrategyConfig();        strategyConfig.setEntityLombokModel(true);        strategyConfig.setNaming(NamingStrategy.underline_to_camel);        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);        autoGenerator.setStrategy(strategyConfig);        autoGenerator.execute();    }}

Spring Boot + MyBatis Plus 打包应用,直接发布 阿里云 上云

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MyBatis Plus快速入门 的相关文章

  • threejs加载3D模型例子

    加载3D模型 首先要引入ColladaLoader加载器 xff0c Collada是一个3D模型交换方案 xff0c 即不同的3D模型可以通过Collada进行相互转换 xff0c 言外之意 xff0c threejs可以使用Collad
  • threejs坐标转换

    屏幕坐标转three js坐标 将屏幕坐标转变成threejs空间坐标 xff1a span class hljs function span class hljs keyword function span span class hljs
  • 搭建GitLab+Jenkins持续集成环境图文教程

    GitLab是一个代码仓库 xff0c 用来管理代码 Jenkins是一个自动化服务器 xff0c 可以运行各种自动化构建 测试或部署任务 所以这两者结合起来 xff0c 就可以实现开发者提交代码到GitLab xff0c Jenkins以
  • threejs-经纬度转换成xyz坐标的方法

    用threejs做3D应用时 xff0c 很经常会接触到球状物体 xff0c 比如说地球 xff0c 要定义球上的一点 xff0c 用经纬度是常用的办法 现在 xff0c 我们要在北京这个地方标一个点 xff0c 北京的坐标为 北纬39 9
  • HTML5 响应式图片

    现在上网设备越来越多 xff0c 各种设备的屏幕千差万别 xff0c 如果只用一张图片去涵盖所有的设备 xff0c 一是可能会造成某些设备上显示效果不佳 xff0c 比如使用了一张低清晰度的图 xff0c 而网页运行在一个高清大屏里 xff
  • 使用EventBus通讯不成功

    最近在开发一个直播app的项目 xff0c 遇到一个需求是当用户点击 退出登录 这个操作时 xff0c 回到登录界面 xff0c 让用户重新登录 这个需求实现起来一点都不难 xff0c 不就是点击退出登录后 xff0c Intent到Log
  • 怎么使用CTreeListCtrl

    代码路径 xff1a http www codeproject com KB tree ctreelistctrl aspx 1 怎么在CTreeListCtrl中使用edit或者combobox 例如双击修改某个item 重载OnLBut
  • android backtrace实现

    前景 backtrace 文档 说明 通过数组获取调用栈 一般获取的是内存地址 借助dladdr获取地址信息 计算可执行文件中的偏移地址 实现 有的没有实现backtrace但是大多都支持unwind 利用unwind实现类似 backtr
  • 【详细教程】阿里云ECS服务器搭建

    一 服务器搭建的网址入口 xff1a 如果您之前没有用过 xff0c 恭喜您 xff0c 是有试用资格的 有试用资格 xff1a 点击进入阿里云云产品试用中心 xff0c 选择下图产品 xff0c 点击试用30天 如果未注册 xff0c 需
  • Matlab绘图-详细,全面(二维&三维等)

    原文 Matlab绘图 xff08 图像为本人所绘 xff09 强大的绘图功能是Matlab的特点之一 xff0c Matlab提供了一系列的绘图函数 xff0c 用户不需要过多的考虑绘图的细节 xff0c 只需要给出一些基本参数就能得到所
  • SpotBugs-IDE插件扫描

    安装 在 Intellij IDE 的Plugins中搜索 SpotBugs 并 安装 设置 打开IDE Settings xff0c 选择 Tools SpotBugs 根据实际情况进行配置 比如选择分析投入 xff0c 分析等级 xff
  • 【C语言】vsnprintf函数的使用

    标题 C语言 vsnprintf函数的使用 提示 xff1a 文章写完后 xff0c 目录可以自动生成 xff0c 如何生成可参考右边的帮助文档 文章目录 标题 C语言 vsnprintf函数的使用前言一 vsnprintf是什么 xff1
  • [python]编写程序产生 ISBN 号的校验位。

    64 MADE BY YWL XJTU python编写程序产生 ISBN 号的校验位 编写程序产生 ISBN 号的校验位 任何新出版的图书都配有 ISBN 号 xff0c 2007 年以前是由 10 位数字加上3个连字符组成的 ISBN
  • python基于内置模块smtplib、email实现163邮箱发送邮件(附完整代码,可直接使用)

    一 获取发送者163邮箱授权密码 第一步 登录邮箱 https mail 163 com 第二步 点击右上角切换回旧版 新版实在没找到在哪 第三步 打开 POP3 SMTP IMAP 设置 第四步 开启POP3 SMTP 服务 第五步 拿到
  • 极速配置VScode C++运行环境

    VScode 极速配置C 43 43 环境及必备插件 Visual Studio Code 简称 VS Code VSC 是一款免费开源的现代化轻量级代码编辑器 xff0c 支持几乎所有主流的开发语言的语法高亮 智能代码补全 自定义热键 括
  • 题目49:输入两个正整数 m 和 k,其中1 < m < 100000,1 < k < 5 ,判断 m 能否被19整除,且恰好含有k个3,如果满足条件,则输出YES,否则,输出NO。

    题目转载 xff1a http python wzms com s 1 42 题目描述 输入两个正整数 m 和 k xff0c 其中1 lt m lt 100000 xff0c 1 lt k lt 5 xff0c 判断 m 能否被19整除
  • Linux 监控网络流量

    文章目录 bmoniftopnethogs bmon sudo apt get install bmon 通过 选择网卡 xff1b 输入 g 控制流量面板的显示和隐藏 xff1b 输入 d 控制详情信息的显示和隐藏 xff1b 输入 q
  • CentOS7.2 在GUI下关闭X Server

    有时候需要关闭X Server xff0c 例如在安装NVIDIA驱动的时候 xff0c 需要关闭X Server xff0c 我们可以通过服务来关闭 首先看下服务 root span class hljs variable 64 soft
  • 用c语言实现 将src指向的字符串追加到dest指向字符串的后面

    实现char my strcat char dest char src 函数 返回 xff1a dest字符串的地址 功能 xff1a 将src指向的字符串追加到dest指向字符串的后面 例如 xff1a char dest 10 61 3
  • CoreData 实体之间的关系

    1 Cascade 级联关系 2 Deny 禁止 3 Nullify 作废 当实体之间创建了关系的时候 xff0c 我们需要判断是否建立级联关系 例如 人和身份证是一对一的 两者之间关系反转 即 人有身份证 xff0c 身份证包含人 当删除

随机推荐