MyBatis-Plus 入门与进阶教程

news2024/9/19 10:34:33

本教程将带领你快速上手 MyBatis-Plus,涵盖其基本功能、常用注解以及插件的使用。我们将通过代码实例一步步展示如何在实际项目中应用 MyBatis-Plus。

1. 快速开始

1.1 添加依赖

pom.xml 中添加以下依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.7</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

1.2 配置数据源

application.yml 中配置 MySQL 数据源信息,并启用 MyBatis 日志打印:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    username: root
    password: 111111

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

1.3 创建启动类

在启动类中添加 @MapperScan 注解,指定 Mapper 接口所在包:

@SpringBootApplication
@MapperScan("com.java.mybatisplus.mapper")
public class MybatisPlusApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusApplication.class, args);
    }
}

1.4 定义实体类与 Mapper 接口

创建 User 实体类与 UserMapper 接口:

package com.java.mybatisplus.dao;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
package com.java.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.java.mybatisplus.dao.User;

public interface UserMapper extends BaseMapper<User> {
}

1.5 编写测试代码

通过 JUnit 测试 UserMapper 的基本查询功能:

package com.java.mybatisplus;

import com.java.mybatisplus.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class MybatisPlusApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        userMapper.selectList(null).forEach(System.out::println);
    }
}

2. 基本增删改查

MyBatis-Plus 提供了强大的 BaseMapper 接口,用于实现 CRUD 操作。我们可以直接在 UserMapper 中继承 BaseMapper<User> 来获得这些基本功能。

2.1 插入数据

@Test
public void testInsert() {
    User user = new User(null, "张三", 32, "zhangsan@atguigu.com");
    int res = userMapper.insert(user);
    System.out.println(res);
    System.out.println(user.getId()); // 自动生成的 ID
}

2.2 删除数据

通过 ID 删除:

@Test
public void testDeleteById(){
    int result = userMapper.deleteById(1826148003704561665L);
    System.out.println(result);
}

通过批量 ID 删除:

@Test
public void testDeleteByIds(){
    List<Integer> idList = Arrays.asList(1, 2, 3);
    int result = userMapper.deleteBatchIds(idList);
    System.out.println(result);
}

2.3 更新数据

@Test
public void testUpdateById(){
    User user = new User(1826149526211735553L,"李四",32,"zhangsan@atguigu.com");
    int result = userMapper.updateById(user);
    System.out.println(result);
}

2.4 查询数据

通过 ID 查询:

@Test
public void testSelectById(){
    User user = userMapper.selectById(1826149526211735553L);
    System.out.println(user);
}

通过条件查询:

@Test
public void testSelectList(){
    List<User> users = userMapper.selectList(null);
    users.forEach(System.out::println);
}

3. 常用注解

MyBatis-Plus 提供了一系列注解来简化数据库表与实体类之间的映射。

3.1 @TableName

当数据库表名与实体类名不一致时,可以使用 @TableName 注解指定表名:

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("t_user")
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

3.2 @TableId

当数据库表的主键字段名与实体类中的字段名不一致时,可以使用 @TableId 注解指定主键:

@TableId(value = "uid", type = IdType.ASSIGN_ID)
private Long id;

3.3 @TableField

当数据库字段与实体类属性名不一致时,可以使用 @TableField 注解:

@TableField("username")
private String name;

3.4 @TableLogic

使用 @TableLogic 注解实现逻辑删除功能:

@TableLogic(value = "0", delval = "1")
private Integer isDeleted;

4. 条件构造器

MyBatis-Plus 提供了强大的条件构造器(Wrapper)用于构建复杂的查询条件。

4.1 QueryWrapper

QueryWrapper 用于构建查询条件:

QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.like("username", "张")
            .between("age", 20, 30)
            .isNotNull("email");
List<User> users = userMapper.selectList(queryWrapper);

4.2 UpdateWrapper

UpdateWrapper 用于构建更新条件:

UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
userUpdateWrapper.set("age", 19)
                 .set("email", "test@atguigu.com")
                 .like("username", "张三")
                 .and(i -> i.gt("age", 20).or().isNull("email"));
int result = userMapper.update(null, userUpdateWrapper);
System.out.println(result);

4.3 LambdaQueryWrapper 和 LambdaUpdateWrapper

LambdaQueryWrapperLambdaUpdateWrapper 可以使用 Lambda 表达式来避免硬编码字段名:

@Test
public void testLambdaQueryWrapper() {
    LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
    lambdaQueryWrapper.like(User::getName, "张")
            .orderByDesc(User::getAge);
    List<User> users = userMapper.selectList(lambdaQueryWrapper);
    users.forEach(System.out::println);
}
@Test
public void testLambdaUpdateWrapper() {
    LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
    lambdaUpdateWrapper.set(User::getAge, 30)
            .eq(User::getName, "张三");
    userMapper.update(null, lambdaUpdateWrapper);
}

5. 插件

MyBatis-Plus 提供了分页插件等功能,通过简单配置即可使用。

5.1 分页插件

在配置类中添加分页插件:

package com.java.mybatisplus.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan("com.java.mybatisplus.mapper")
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

5.2 分页查询

使用分页插件进行分页查询:

@Test
public void testSelectPage(){
    IPage<User> page = new Page<>(1, 2);
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.gt("age", 20);
    IPage<User> userPage = userMapper.selectPage(page, queryWrapper);
    List<User> userList = userPage.getRecords();
    long total = userPage.getTotal();
    System.out.println("总数: " + total);
    userList.forEach(System.out::println);
}

6.代码生成器

方式一:代码运行

  1. 添加依赖
		<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.5.7</version>
        </dependency>
        <!-- FreeMarker -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.31</version> <!-- Use the version compatible with your mybatis-plus version -->
        </dependency>
  1. 执行代码
package com.java.mybatisplus.generator;

import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.sql.Types;
import java.util.Collections;

/**
 * @author DNY
 * @create 2024-08-21 19:39
 */
public class CodeGenerator {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC";
        String username = "root";
        String password = "111111";

        FastAutoGenerator.create(url, username, password)
                .globalConfig(builder -> {
                    builder.author("baomidou") // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .outputDir("D:\\JavaCode\\java-project-test\\mybatis-plus\\src\\main\\java\\com\\java\\mybatisplus\\generator"); // 指定输出目录
                })
                .dataSourceConfig(builder ->
                        builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                            int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                            if (typeCode == Types.SMALLINT) {
                                // 自定义类型转换
                                return DbColumnType.INTEGER;
                            }
                            return typeRegistry.getColumnType(metaInfo);
                        })
                )
                .packageConfig(builder ->
                        builder.parent("com.java.mybatisplus") // 设置父包名
                                .moduleName("mybatis-plus") // 设置父包模块名
                                .pathInfo(Collections.singletonMap(OutputFile.xml, "D:\\JavaCode\\java-project-test\\mybatis-plus\\src\\main\\java\\com\\java\\mybatisplus\\generator")) // 设置mapperXml生成路径
                )
                .strategyConfig(builder ->
                        builder.addInclude("t_user") // 设置需要生成的表名
                                .addTablePrefix("c_") // 设置过滤表前缀
                )
                .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();
    }
}

方式二:MybatisX

在这里插入图片描述

结语

本教程涵盖了 MyBatis-Plus 的基本使用方法和一些常用的高级功能。通过这些知识,你可以在项目中更高效地进行数据库操作,并充分利用 MyBatis-Plus 的特性来简化开发工作。希望本教程能为你提供帮助,在实际项目中取得更好的成果。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2092257.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Hexo系列】【7】Butterfly主题使用及美化

本期将为大家讲解Hexo Butterfly主题的使用。 1. 主题介绍 hexo-theme-butterfly是基于 Molunerfinn 的 hexo-theme-melody 的基础上进行开发的&#xff0c;当前版本是v4.13.0。 主题官网&#xff1a;https://github.com/jerryc127/hexo-theme-butterfly 官网效果图&#x…

Unity(2022.3.41LTS) - 3D关节

目录 零. 简介 一、关节的类型及特点 二、关节的使用方法 三、关节的应用场景 四. 实例效果 零. 简介 在 Unity 中&#xff0c;关节&#xff08;Joints&#xff09;是实现物理模拟和复杂交互效果的重要组件。以下是对 Unity 关节更详细的介绍&#xff1a; 一、关节的类型…

JDBC中的execute, executeQuery, 和 executeUpdate方法区别

JDBC中的execute, executeQuery, 和 executeUpdate方法区别 1、execute(String sql)2、executeQuery(String sql)3、executeUpdate(String sql) &#x1f496;The Begin&#x1f496;点点关注&#xff0c;收藏不迷路&#x1f496; 1、execute(String sql) 功能&#xff1a;执…

Day89 代码随想录打卡|贪心算法篇---划分字母区间

题目&#xff08;leecode T763&#xff09;&#xff1a; 给你一个字符串 s 。我们要把这个字符串划分为尽可能多的片段&#xff0c;同一字母最多出现在一个片段中。 注意&#xff0c;划分结果需要满足&#xff1a;将所有划分结果按顺序连接&#xff0c;得到的字符串仍然是 s …

国产数据库打败Oracle?不存在的!

XC背景下国产数据库替代工程进行的如火如荼&#xff0c;数据库圈特别是Oracle的从业人员&#xff0c;既感受到深深的危机感&#xff0c;又带着些许的不甘&#xff0c;这种不甘主要来自于技术层面。 技术人员也有武士道精神&#xff0c;谁能打败我我服谁&#xff0c;谁的技术比…

如何判断儿童是否患有自闭症

自闭症&#xff0c;也被称为孤独症&#xff0c;是一种复杂的神经发育障碍&#xff0c;其症状通常在儿童早期就开始显现。面对孩子的成长过程&#xff0c;家长和教育者如何准确判断孩子是否患有自闭症&#xff0c;是一个至关重要的问题。 我们需要关注孩子的社交行为。自闭症儿童…

java之浅拷贝、深拷贝

1、java数据类型 java数据类型分为基本数据类型和引用数据类型 基本数据类型&#xff1a;byte、short、int、long、float、double、boolean、char。 引用类型&#xff1a;常见的有类、接口、数组、枚举等。 2、浅拷贝、深拷贝 以下探讨的浅拷贝、深拷贝是通过Object类中的cl…

Python matplotlib绘图 plt.barh 水平条形图调整顺序逆序排列

使用matplotlib 中的 plt.barh 绘制水平条形图时&#xff0c;数据的排列顺序默认由小到大排列&#xff0c;即数据条由短到长排列展示&#xff0c;如果想让数据条由长到短排列展示&#xff0c;可尝试以下代码。 import matplotlib.pyplot as plt import pandas as pd import nu…

MySQL——基础操作

一、数据库的创建 1.1 库的创建 在使用数据库时&#xff0c;最先操作的是创建一个数据库。使用语法如下&#xff1a; CREATE DATABASE [IF NOT EXISTS] database_name [[DEFAULT] CHARSETcharset_name] [[DEFAULT] COLLATEcollation_name]; 对上述语句进行简单说明&#xf…

【秋招笔试题】讨厌冒泡排序

题解&#xff1a;免费的操作是分别在奇偶下标进行排序&#xff0c;收费的操作会改变他们下标的奇偶性&#xff0c;那么直接统计在排序后有多少元素的下标发生变化了即可。 #include <iostream> #include <vector> #include <algorithm> #include "map&…

猫头虎 分享:Python库 XGBoost 的简介、安装、用法详解入门教程

猫头虎 分享&#xff1a;Python库 XGBoost 的简介、安装、用法详解入门教程 &#x1f3af; ✨ 引言 今天猫头虎收到一位粉丝的提问&#xff1a;“猫哥&#xff0c;我在项目中需要用到 XGBoost&#xff0c;可是对它的了解不够深入&#xff0c;不知道从哪开始&#xff0c;能否详…

线性查找表的应用:用户登录注册程序

线性查找表是很简单的数据结构和算法。网站的用户登录注册时是基本的功能。本文首先给出线性查找表的基本实现&#xff0c;然后给出在用户登录注册的程序流程图&#xff0c;并将线性查找表应用到用户查询这一具体任务&#xff0c;并基于 Python 语言在控制台实现用户注册、登录…

ComfyUI使用Flux模型

ComfyUI是一个强大的用户界面&#xff0c;支持多种图像处理和生成模型&#xff0c;而Flux是一系列由Black Forest Labs开发的扩散模型。 准备工作 1. 下载所需文件 下载地址&#xff1a; comfyanonymous/flux_text_encoders at main (hf-mirror.com)https://hf-mirror.com/…

django企业开发实战-学习小结

写在前面 初次阅读此书是三年前&#xff0c;当时没经历过完整的项目 觉得这书就是扯淡 后来经历过项目加班与毒打 今天再翻开此书 觉得实乃不可多得之物 花些时间啃下来吧 需求 需求文档 写文档&#xff0c;列举需要实现的功能&#xff0c;详细列举&#xff0c;不考虑技术实…

Leetcode Hot 100刷题记录 -Day6(滑动窗口)

无重复字符的最长子串 问题描述&#xff1a; 给定一个字符串 s &#xff0c;请你找出其中不含有重复字符的 最长子串的长度。 示例 1: 输入: s "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc"&#xff0c;所以其长度为 3。示例 2: 输入: s …

10:Logic软件原理图中添加电源与GND

Logic软件原理图中添加电源与GND

“品牌VS套路:华为、格行、中兴随身WiFi谁才是真良心?“

咱们打工人月末有三光&#xff0c;工资花光&#xff0c;流量用光&#xff0c;话费剩光光。 不过除了工资没办法解决&#xff0c;剩下两个还能抢救一下 提起这个事情的起因是我发现现在的互联网平台到处都是推销随身WiFi的&#xff0c;什么零月租、几百G流量不限速不限量啥的&…

Cortex-A7支持的内存类型详解及配置举例

0 参考资料 Introduction to memory protection unit management on STM32 MCUs.pdf ARM ArchitectureReference Manual ARMv7-A and ARMv7-R edition.pdf 1 Cortex-A7支持的内存类型详解 1.1 内存类型 ARM架构处理器支持的内存类型分为三种&#xff0c;分别是Normal memory&…

airflow看不到任务日志解决方案

1. 基础信息 airflow 版本&#xff1a;2.5.3 2. 问题现象 airflow web-server 界面&#xff0c;看到某些任务的具体运行日志&#xff0c;只有少量日志&#xff0c;如下图所示&#xff1a; 具体日志内容如下&#xff1a; na-fudao-data-airflow-test-2-21.alibji.zybang.com…

某视频云平台存在未授权窃取用户凭据漏洞

我和你一样&#xff0c;历经破碎、痛苦的生活&#xff0c;却未垮掉&#xff0c;每一日都从承受的苦难中&#xff0c;再一次将额头浸入光明 漏洞详情&#xff1a; 某视频云平台存在未授权访问漏洞&#xff0c;攻击者可以直接访问平台的API接口文档&#xff0c;从而获取系统的A…