首页 > 其他分享 >mybatis-plus入门

mybatis-plus入门

时间:2022-11-21 15:44:27浏览次数:55  
标签:mybatisplus 入门 baomidou Wrapper plus mybatis import com public

1、快速开始

1.1、现有一张 User 表,其表结构如下

id name age emali
1 Jone 18 [email protected]
2 Jack 20 [email protected]
3 Tom 28 [email protected]
4 Sandy 21 [email protected]
5 Billie 24 [email protected]
  • SQL语句
DROP TABLE IF EXISTS user;

CREATE TABLE `user` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `name` varchar(30) DEFAULT NULL COMMENT '姓名',
  `age` int DEFAULT NULL COMMENT '年龄',
  `email` varchar(50) DEFAULT NULL COMMENT '邮箱',
  `is_deleted` int NOT NULL DEFAULT '0' COMMENT '逻辑删除',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

DELETE FROM user;

INSERT INTO user (id, name, age, email,is_deleted) VALUES
(1, 'Jone', 18, '[email protected]',0),
(2, 'Jack', 20, '[email protected]',0),
(3, 'Tom', 28, '[email protected]',0),
(4, 'Sandy', 21, '[email protected]',0),
(5, 'Billie', 24, '[email protected]',0);

1.2、引入依赖

  • mybatis-plus-boot-starter
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.11</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

1.3、配置数据库连接,开启控制台SQL语句输出

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://114.67.111.175:3306/test
    username: wq
    password: 123456
#开启控制台日志
mybatis-plus:
  configuration:
    #控制台打印sql语句方便调试sql语句执行错误
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    #这个不在控制台打印查询结果,但是在log4j2中打印
    #log-impl: org.apache.ibatis.logging.log4j2.Log4j2Impl
  • 在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:
@SpringBootApplication
@MapperScan("com.wanqi.mybatisplus.mapper")
public class Application {

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

}

1.4、编码

  • 实体类User
package com.wanqi.mybatisplus.pojo;


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

@TableName("user") //指定表名
public class User {
    //type = IdType.AUTO自增字段需要修改数据库主键为自增
    //value指定对应主键字段名,type指定id生成策略(默认策略为雪花算法)
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;
    //value数据库字段值
    @TableField(value = "name")
    private String name;
    private Integer age;
    private String email;
    private Integer isDeleted;


    public User(Long id, String name, Integer age, String email) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.email = email;
    }
    public User(String name, Integer age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }

    public User() {
    }

    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 Integer getAge() {
        return age;
    }

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

    public String getEmail() {
        return email;
    }

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

   public Integer getIsDeleted() {
        return isDeleted;
    }

    public void setIsDeleted(Integer isDeleted) {
        this.isDeleted = isDeleted;
    }

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

  • 编写 Mapper 包下的 UserMapper接口
import com.wanqi.mybatisplus.pojo.User;
import org.springframework.stereotype.Repository;

@Repository
public interface UserMapper extends BaseMapper<User> {

}

1.5、测试使用

package com.wanqi.mybatisplus;

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

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@SpringBootTest
class MybatisPlusApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        userMapper.insert(new User( "古力娜扎", 18, "[email protected]"));

        List<User> userList = userMapper.selectList(null);
        userList.forEach(System.out::println);
    }
}

2、批量操作

2.1、增加Service 层代码

package com.wanqi.mybatisplus.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.wanqi.mybatisplus.pojo.User;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/9/1
 * @Author wandaren
 */
public interface UserService extends IService<User> {
}

  • 注意 UserServiceImpl 必须要继承 MP 框架中的 ServiceImpl,不然要重写很多方法。
package com.wanqi.mybatisplus.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wanqi.mybatisplus.mapper.UserMapper;
import com.wanqi.mybatisplus.pojo.User;
import org.springframework.stereotype.Service;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/9/1
 * @Author wandaren
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> 
    implements UserService{
}

2.2、测试使用

package com.wanqi.mybatisplus;

import com.wanqi.mybatisplus.mapper.UserMapper;
import com.wanqi.mybatisplus.pojo.User;
import com.wanqi.mybatisplus.service.UserServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@SpringBootTest

class MybatisPlusApplicationTests {
    @Autowired
    private UserServiceImpl userService;

    @Test
    void contextLoads() {
        Collection<User> userList = new ArrayList<>();
        userList.add(new User("hhh", 18, "[email protected]"));
        userList.add(new User("sss", 18, "[email protected]"));
        userList.add(new User("ddd", 18, "[email protected]"));
        userService.saveBatch(userList);
        System.out.println(userService.list());
    }
}

3、Service CURD

3.1、save

// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);

image.png

3.2、saveOrUpdate

// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);

image.png

3.3、remove

// 根据 entity 条件,删除记录
boolean remove(Wrapper<T> queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map<String, Object> columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);

image.png

3.4、update

// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper<T> whereWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);

image.png

3.5、get

// 根据 ID 查询
T getById(Serializable id);
// 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
// 根据 Wrapper,查询一条记录
Map<String, Object> getMap(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

image.png

3.6、List

// 查询所有
List<T> list();
// 查询列表
List<T> list(Wrapper<T> queryWrapper);
// 查询(根据ID 批量查询)
Collection<T> listByIds(Collection<? extends Serializable> idList);
// 查询(根据 columnMap 条件)
Collection<T> listByMap(Map<String, Object> columnMap);
// 查询所有列表
List<Map<String, Object>> listMaps();
// 查询列表
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);
// 查询全部记录
List<Object> listObjs();
// 查询全部记录
<V> List<V> listObjs(Function<? super Object, V> mapper);
// 根据 Wrapper 条件,查询全部记录
List<Object> listObjs(Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录
<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

image.png

3.7、page

// 无条件分页查询
IPage<T> page(IPage<T> page);
// 条件分页查询
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper);
// 无条件分页查询
IPage<Map<String, Object>> pageMaps(IPage<T> page);
// 条件分页查询
IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper);

image.png

4、逻辑删除

  • 方式一:使用注解TableLogic
// value逻辑未删除值,delval逻辑删除值
@TableLogic(value = "0", delval = "1")
private Integer isDeleted;
  • 方式二:使用全局配置
mybatis-plus:
  global-config:
    db-config:
      logic-delete-field: isDeleted # 全局逻辑删除的实体字段名
      logic-delete-value: 1 # 逻辑已删除值(默认为 1)
      logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

5、分页

  • 配置
package com.wanqi.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.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/9/24
 * @Author wandaren
 */
@Configuration
public class CustomMyBatisPlusConfig {
    /**
     * 分页插件,一缓和二缓遵循mybatis的规则
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
        // paginationInnerInterceptor.setOverflow(false);
        // 设置最大单页限制数量,默认 500 条,-1 不受限制
        // paginationInnerInterceptor.setMaxLimit(500L);
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }

}
  • 测试
    @Test
    void page() {
        long l = System.currentTimeMillis();
        Page<VoteRecord> page = new Page<>(99999, 20);
        final Page<VoteRecord> voteRecordPage = voteRecordMapper.selectPage(page, null);
        voteRecordPage.getRecords().forEach(System.out::println);
        System.out.println(System.currentTimeMillis() -l);
    }

标签:mybatisplus,入门,baomidou,Wrapper,plus,mybatis,import,com,public
From: https://www.cnblogs.com/wandaren/p/16906568.html

相关文章

  • 使用mybatis-plus代码生成器生成代码框架
    使用mybatis-plus代码生成器生成代码框架一.首先引入依赖<!--连接MySQL--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring......
  • 记一次mybatis检查
    搭建学习springcloud,添加数据源,控制台不报错, mybatis无法使用。1.启动控制台报错:配置文件未生效编译后target目录下无mapper.xml和bootstarp.yaml。  --先手动复......
  • mybatis流式查询与分页插件
    1、流式查询1、实体类packagecom.wanqi.pojo;importjava.util.Date;/***@DescriptionTODO*@Version1.0.0*@Date2022/9/12*@Authorwandaren*/......
  • 篇(17)-Asp.Net Core入门实战-文章管理之文章类别管理(Linq子查询)
    篇(17)-Asp.NetCore入门实战-文章管理之文章类别的管理如果要做一个CMS系统,那么文章管理算是入门,文章管理附带一个类别管理,用来对文章进行类别区分。所以,本章简单讲一些......
  • 2.3创建mybatis的逆向工程
    1.1创建mybatis的逆向工程1,同步请求和异步请求的区别:同步请求:浏览器窗口发出的请求,响应信息返回到浏览器窗口,所以会进行全局刷新。异步请求:ajax发出的请求,响应......
  • linux入门介绍
    Linux的命令基本格式为:[root@localhost~]#命令[选项][参数][]中代表可选项即也可不带选项和参数shell   翻译官 将人类使用的高级语言 转换成二进制 ce......
  • Mybatis查询返回Map
    1/**2*查询产品的医保名称、省标名称3*@paramproductIds4*@return5*/6@MapKey("productId")7publicMap<Long,Provinc......
  • PowerDesigner入门使用操作
    PowerDesigner是一个做开发设计很常用的工具软件,同时还有Rose也可以,都是当前软件开发最著名的建模设计及软件之一,下面讲解简单的应用。步骤:1.现在各版本非常多,本教程使用16......
  • ASP.NET Core 之 Identity 入门(二)
    前言在上篇文章中讲了关于Identity需要了解的单词以及相对应的几个知识点,并且知道了Identity处在整个登入流程中的位置,本篇主要是在.NET整个认证系统中比较重要的......
  • ASP.NET Core 之 Identity 入门(三)
    前言在上一篇文章中,我们学习了CookieAuthentication中间件,本篇的话主要看一下Identity本身。最早2005年ASP.NET2.0的时候开始,Web应用程序在处理身份验证和授权......