MyBatis-Plus的基础增删改查

目录

MyBatis-Plus介绍

简介

特性

MyBatis-Plus的增删改查

前期准备

添加操作

添加一条数据

获取主键 id 的值

更新操作

通过 id 进行更新操作

删除操作

根据主键 id 删除

根据条件删除数据,条件封装到 Map 中

批处理删除:多个主键 id 删除多条数据

查询操作

根据主键 id 进行查询

批量查询,根据多个主键 id 进行查询

根据 Map 条件 查询


MyBatis-Plus介绍

简介

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

特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作,BaseMapper
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求,简单的CRUD操作不用自己编写。
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用(自动生成代码)
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

MyBatis-Plus的增删改查

前期准备

  • 创建一个数据库 mybatisplus

  • 创建 user

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
);
  • 创建 springboot 工程
    • 导入对应 maven 坐标
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cmy</groupId>
    <artifactId>mybatis_plus</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis_plus</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.0</version>
        </dependency>

        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
    • mysql数据库相关配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1/mybatisplus?useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
    • mybatis-plus 日志信息配置
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    • 创建实体类 User
package com.cmy.mybatis_plus.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;

/**
 * 实体类 user
 */
public class User {
    /**
     * 指定主键id生成的方式
     * value 是主键字段的名称,如果是id,可以不用写
     * type 指定主键的类型,主键的值如何生成。idType.AUTO 自动增长
     */
    @TableId(
            value = "id",
            type = IdType.AUTO
    )
    private Long id;
    private String name;
    private String email;
    private Integer age;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

    • 自定义 User 的 Mapper 接口
package com.cmy.mybatis_plus.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cmy.mybatis_plus.entity.User;

/**
 * 自定义 Mapper 接口,就是 dao 接口
 * 1. 实现BaseMapper
 * 2. 指定实体类(泛型)
 *
 * BaseMapper 是 MP 框架中的对象,定义了 17 个操作方法(CRUD)
 */
public interface UserMapper extends BaseMapper<User> {
}

添加操作

添加一条数据

/**
 * 使用自动注入,注入 Mapper 对象
 */
@Autowired
private UserMapper userMapper;

@Test
public void testUserInsert() {
    // 创建 User 对象
    User user = new User();
    user.setName("zs");
    user.setAge(20);
    user.setEmail("[email protected]");

    // 调用 UserMapper 的方法,也就是父接口 BaseMapper 中的方法
    int result = userMapper.insert(user);
    System.out.println("insert 的结果:" + result);
}

获取主键 id 的值

/**
 * 测试
 * 添加数据后,获取主键id的值
 */
@Test
public void testUserInsertGetId() {
    // 创建 User 对象
    User user = new User();
    user.setName("李四");
    user.setAge(21);
    user.setEmail("[email protected]");

    // 调用 UserMapper 的方法,也就是父接口 BaseMapper 中的方法
    int rows = userMapper.insert(user);
    System.out.println("insert user rows:" + rows);

    // 获取主键 id 的值
    Long id = user.getId();
    System.out.println("主键 id 的值:" + id);
}

更新操作

通过 id 进行更新操作

/**
 * 使用自动注入,注入 Mapper 对象
 */
@Autowired
private UserMapper userMapper;

@Test
public void testUpdateById() {
    User user = new User();
    user.setName("李四(修改后)");
    user.setAge(25);
    user.setId(3L);

    // 执行更新操作
    int rows = userMapper.updateById(user);
    System.out.println("update rows: " + rows);
}

删除操作

根据主键 id 删除

/**
 * 使用自动注入,注入 Mapper 对象
 */
@Autowired
private UserMapper userMapper;

@Test
public void testDeleteById() {
    // DELETE FROM user WHERE id=?
    int i = userMapper.deleteById(3);
    System.out.println("delete rows: " + i);
}

根据条件删除数据,条件封装到 Map 中

/**
 * 使用自动注入,注入 Mapper 对象
 */
@Autowired
private UserMapper userMapper;

@Test
public void testDeleteByMap() {
    // 创建 Map 对象,保存条件值
    Map<String, Object> map = new HashMap<>();
    // put("表的字段名", 条件值),可以封装多个条件
    map.put("name", "zs");
    map.put("age", 20);
    // 调用删除方法
    // DELETE FROM user WHERE name = ? AND age = ?
    int i = userMapper.deleteByMap(map);
    System.out.println("delete rows: " + i);
}

批处理删除:多个主键 id 删除多条数据

/**
 * 使用自动注入,注入 Mapper 对象
 */
@Autowired
private UserMapper userMapper;

@Test
public void testDeleteBatchIds() {

    // 使用 lambda 创建集合
    List<Integer> ids = Stream.of(1, 2, 3, 4, 5).collect(Collectors.toList());
    // 删除操作
    // DELETE FROM user WHERE id IN ( ? , ? , ? , ? , ? )
    int rows = userMapper.deleteBatchIds(ids);
    System.out.println("delete rows: " + rows);

}

查询操作

根据主键 id 进行查询

/**
 * 使用自动注入,注入 Mapper 对象
 */
@Autowired
private UserMapper userMapper;

@Test
public void testSelectById() {
    // SELECT id,name,email,age FROM user WHERE id=?
    User user = userMapper.selectById(6);

    if (user == null) {
        System.out.println("用户不存在");
    } else {
        System.out.println(user);
    }
}

批量查询,根据多个主键 id 进行查询

/**
 * 使用自动注入,注入 Mapper 对象
 */
@Autowired
private UserMapper userMapper;

@Test
public void testSelectBatchIds () {
    // SELECT id,name,email,age FROM user WHERE id IN ( ? , ? , ? , ? , ? )
    List<Integer> ids = Stream.of(4, 6, 7, 9, 11).collect(Collectors.toList());

    List<User> userList = userMapper.selectBatchIds(ids);
    for (User user : userList) {
        System.out.println(user);
    }
}

根据 Map 条件 查询

/**
 * 使用自动注入,注入 Mapper 对象
 */
@Autowired
private UserMapper userMapper;

@Test
public void testSelectByMap() {
    Map<String, Object> map = new HashMap<>();
    map.put("name", "李四");
    map.put("age", 21);

    // 根据 Map 查询
    // SELECT id,name,email,age FROM user WHERE name = ? AND age = ?
    List<User> users = userMapper.selectByMap(map);
    for (User user : users) {
        System.out.println(user);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_52317961/article/details/128299880