MyBatisPlus——内置Mapper方面的CRUD

目录

1、相关前提步骤

1)、创建数据库表对应的实体类

2)、接着只需要继续创建一个UserMapper接口,并继承BaseMapper接口

3)、后面就可以进行相关的CRUD的操作了

2、增

1)、insert方法

3、删

1)、delete方法

2)、deleteBatchIds方法

3)、deleteById法

4)、deleteByMap法

4、改

1)、update方法

2)、updateById方法

5、查

1)、条件查询

(1)、不加条件全部查询

(2)、单条件查询

(3)、多条件查询

(4)、小于查询

(5)、大于查询

(6)、不等于查询

(7)、大于和等于查询

(8)、模糊查询

(9)、SQL组合查询 inSQL (下列两个SQL语句进行组合查询)

(10)、降序排序查询

(11)、升序排序查询

(12)、根据主键ID查询

(13)、根据多主键ID查询

(14)、Map等值判断查询,且Map只能做等值判断,逻辑判断需要使用Wrapper来处理

(15)、查询相关数量,比如说id大于1的

(16)、将查询结果集封装到Map中

(17)、查询单个数据

2)、分页查询

(1)、基本分页查询

(2)、分页查询,以map集合的形式返回

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

(1)、定义实体类

(2)、自定义SQL查询


        MyBatisPlus 内置通用 Mapper,我们仅需要继承 BaseMapper,通过少量配置即可实现单表大部分 CRUD 操作,同时其更有强大的条件构造器,满足各类使用需求,且MyBatisPlus通过CRUD封装BaseMapper(opens new window)接口,为MyBatisPlus启东时自动解析实体表关系映射转换为 Mybatis 内部对象注入容器 。且MyBatisPlus 不需要Mapper.XML这个模块就可以进行数据库的操作。

1、相关前提步骤

1)、创建数据库表对应的实体类

package com.exerciseitems.mybatisplus.entity;
import com.baomidou.mybatisplus.annotation.*;
import com.exerciseitems.mybatisplus.enums.AgeEnum;
import com.exerciseitems.mybatisplus.enums.StatusEnum;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.Date;

/**
 * @author : [LiuYanQiang]
 * @version : [v1.0]
 * @className : User
 * @description : [描述说明该类的功能]
 * @createTime : [2021/9/11 20:45]
 * @updateUser : [LiuYanQiang]
 * @updateTime : [2021/9/11 20:45]
 * @updateRemark : [描述说明本次修改内容]
 */
@Data
@TableName("user")
@Accessors(chain = true) //访问器允许链式操作
public class User {
    private String id;
    private String name;
    private Integer age;
    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
    @TableField(value = "is_delete")
    private Integer isDelete;
}

2)、接着只需要继续创建一个UserMapper接口,并继承BaseMapper接口

package com.exerciseitems.mybatisplus.mapper;

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

/**
 * @author : [LiuYanQiang]
 * @version : [v1.0]
 * @className : UserMapper
 * @description : [描述说明该类的功能]
 * @createTime : [2021/9/11 20:48]
 * @updateUser : [LiuYanQiang]
 * @updateTime : [2021/9/11 20:48]
 * @updateRemark : [描述说明本次修改内容]
 */

public interface UserMapper extends BaseMapper<User> {
}

3)、后面就可以进行相关的CRUD的操作了

注,后面实体类使用链式的链式操作需要在实体类上加入注解

//意思是访问器允许链式操作 
@Accessors(chain = true)

2、增

1)、insert方法

(1)、官方提供的接口说明

// 插入一条记录
int insert(T entity);

参数说明

类型

参数名

描述

T

entity

实体对象

(2)、实现方式

User user = new User();
user.setTitle("⼩明");
user.setAge(22);
mapper.insert(user);

3、删

1)、delete方法

(1)、官方提供的接口说明

// 根据 entity 条件,删除记录
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);

参数说明

类型

参数名

描述

Wrapper<T>

wrapper

实体对象封装操作类(可以为 null)

(2)、实现方式

/*
     * @version V1.0
     * Title: delete
     * @author LiuYanQiang
     * @description 使用查询构造器,删除记录
     * @createTime  2021/9/18 10:34
     * @param []
     * @return void
     * ==>  Preparing: UPDATE user SET is_delete=1 WHERE is_delete=0 AND (name LIKE ? AND age = ?)
     * ==> Parameters: %张%(String), 23(Integer)
     * */
    @Test
    void delete(){
        // 查询条件:名字中包含'张'并且年龄等于23
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(User::getName,"张").eq(User::getAge,23);
        System.out.println(mapper.delete(queryWrapper));
    }

2)、deleteBatchIds方法

(1)、官方提供的接口说明

// 删除(根据ID 批量删除)
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

参数说明

类型

参数名

描述

Collection<? extends Serializable>

idList

主键ID列表(不能为 null 以及 empty)

(2)、实现方式

    /*
     * @version V1.0
     * Title: deleteBatchIds
     * @author LiuYanQiang
     * @description 根据 id 批量删除
     * @createTime  2021/9/18 10:38
     * @param []
     * @return void
     * ==>  Preparing: UPDATE user SET is_delete=1 WHERE id IN ( ? , ? , ? ) AND is_delete=0
     * ==> Parameters: 4(Integer), 5(Integer), 6(Integer)
     * */
    @Test
    void deleteBatchIds(){
        System.out.println(mapper.deleteBatchIds(Arrays.asList(4, 5, 6)));
    }

3)、deleteById法

(1)、官方提供的接口说明

// 根据 ID 删除
int deleteById(Serializable id);

参数说明

类型

参数名

描述

Serializable

id

主键ID

(2)、实现方式

    /*
     * @version V1.0
     * Title: deleteById
     * @author LiuYanQiang
     * @description 根据 id 删除一条记录
     * @createTime  2021/9/18 9:33
     * @param []
     * @return void
     * ==>  Preparing: UPDATE user SET is_delete=1 WHERE id=? AND is_delete=0
     * ==> Parameters: 0(Integer)
     * */
    @Test
    void deleteById (){
        System.out.println(mapper.deleteById(0));
    }

4)、deleteByMap法

(1)、官方提供的接口说明

// 根据 columnMap 条件,删除记录
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

参数说明

类型

参数名

描述

Map<String, Object>

columnMap

表字段 map 对象

(2)、实现方式

    /*
     * @version V1.0
     * Title: deleteByMap
     * @author LiuYanQiang
     * @description 通过 Map 封装的条件删除记录
     *              注意:map 写的是数据表中的列名,而非实体类的属性名。比如属性名为 Name,数据表中字段为 name,这里应该写的是 name
     * @createTime  2021/9/18 10:41
     * @param []
     * @return void
     * ==>  Preparing: UPDATE user SET is_delete=1 WHERE name = ? AND age = ? AND is_delete=0
     * ==> Parameters: 张(String), 23(Integer)
     * */
    @Test
    void deleteByMap(){
        Map<String,Object> columnMap = new HashMap<>();
        columnMap.put("name", "张");
        columnMap.put("age", 23);
        System.out.println(mapper.deleteByMap(columnMap));
    }

4、改

1)、update方法

(1)、官方提供的接口说明

// 根据 whereWrapper 条件,更新记录
int update(@Param(Constants.ENTITY) T updateEntity, @Param(Constants.WRAPPER) Wrapper<T> whereWrapper);

参数说明

类型

参数名

描述

T

entity

实体对象 (set 条件值,可为 null)

(2)、实现方式

    /*
     * @version V1.0
     * Title: update
     * @author LiuYanQiang
     * @description 根据 whereWrapper 条件,更新记录
     * @createTime  2021/9/18 10:47
     * @param []
     * @return void
     * ==>  Preparing: UPDATE user SET gender=?, update_time=? WHERE is_delete=0 AND (name LIKE ? AND age = ?)
     * ==> Parameters: 女(String), 2021-09-18 10:54:43.83(Timestamp), %张%(String), 23(Integer)
     * */
    @Test
    void update(){
        // 查询条件:名字中包含'张'并且年龄等于23
        LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.like(User::getName,"张").eq(User::getAge,23);
        // 将满足条件的记录的性别都设置为女
        System.out.println(mapper.update(new User().setGender("女"), updateWrapper));
    }

2)、updateById方法

(1)、官方提供的接口说明

// 根据 ID 修改
int updateById(@Param(Constants.ENTITY) T entity);

参数说明

类型

参数名

描述

Wrapper<T>

updateWrapper

实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)

(2)、实现方式

    /*
     * @version V1.0
     * Title: updateById
     * @author LiuYanQiang
     * @description 根据 ID 修改
     *              如果实体类某个属性为 null,不会更新该属性(且不会把对应的数据库字段值设置为 null)
     * @createTime  2021/9/18 10:56
     * @param []
     * @return void
     * ==>  Preparing: UPDATE user SET name=?, age=?, update_time=? WHERE id=? AND is_delete=0
     * ==> Parameters: 张三(String), 23(Integer), 2021-09-18 10:59:04.894(Timestamp), 2(String)
     * */
    @Test
    void updateById(){
        User user = new User();
        user.setId("2");
        user.setName("张三");
        user.setAge(23);
        System.out.println(mapper.updateById(user));
    } 

5、查

条件参数说明

查询方式

说明

setSqlSelect

设置 SELECT 查询字段

where

WHERE 语句,拼接 + WHERE 条件

and

AND 语句,拼接 + AND 字段=值

andNew

AND 语句,拼接 + AND (字段=值)

or

OR 语句,拼接 + OR 字段=值

orNew

OR 语句,拼接 + OR (字段=值)

eq

等于=

allEq

基于 map 内容等于=

ne

不等于<>

gt

大于>

ge

大于等于>=

lt

小于<

le

小于等于<=

like

模糊查询 LIKE

notLike

模糊查询 NOT LIKE

in

IN 查询

notIn

NOT IN 查询

isNull

NULL 值查询

isNotNull

IS NOT NULL

groupBy

分组 GROUP BY

having

HAVING 关键词

orderBy

排序 ORDER BY

orderAsc

ASC 排序 ORDER BY

orderDesc

DESC 排序 ORDER BY

exists

EXISTS 条件语句

notExists

NOT EXISTS 条件语句

between

BETWEEN 条件语句

notBetween

NOT BETWEEN 条件语句

addFilter

自由拼接 SQL

last

拼接在最后,例如:last("LIMIT 1")

1)、条件查询

(1)、不加条件全部查询

//不加条件全部查询
mapper.selectList(null);

(2)、单条件查询

//单条件查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("name","小明");
mapper.selectList(wrapper);

(3)、多条件查询

//多条件查询
QueryWrapper wrapper = new QueryWrapper();
Map<String,Object> map = new HashMap<>();
map.put("name","小明");
map.put("age","23");
wrapper.allEq(map);
mapper.selectList(wrapper);

(4)、小于查询

//小于查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.lt("age","24");
mapper.selectList(wrapper);

(5)、大于查询

//大于查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.gt("age","24");
mapper.selectList(wrapper);

(6)、不等于查询

//不等于查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.ne("name","小明");
mapper.selectList(wrapper);

(7)、大于和等于查询

//大于和等于查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.ge("age","23");
mapper.selectList(wrapper);

(8)、模糊查询

//模糊查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.like("name","小");
//模糊查询左拼接查询,从“小”   结束like '%小'
wrapper.likeLeft("name","小");
//模糊查询右拼接查询,从“小” 开始  like '小%'
wrapper.likeRight("name","小");
mapper.selectList(wrapper);

(9)、SQL组合查询 inSQL (下列两个SQL语句进行组合查询)

//SQL组合查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.inSql("id","select id from user where id < 30");
wrapper.inSql("age","select age from user where age > 10");
mapper.selectList(wrapper);

(10)、降序排序查询

//降序排序查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.orderByDesc("age");
mapper.selectList(wrapper).forEach(System.out::println);

(11)、升序排序查询

//升序排列查询
QueryWrapper wrapper = new QueryWrapper();
wrapper.orderByAsc("age");
wrapper.having("id>8");
mapper.selectList(wrapper).forEach(System.out::println);

(12)、根据主键ID查询

//根据主键ID查询
mapper.selectById(3)

(13)、根据多主键ID查询

//根据多主键ID查询
mapper.selectBatchIds(Arrays.asList(1,2,3)).forEach(System.out::println);

(14)、Map等值判断查询,且Map只能做等值判断,逻辑判断需要使用Wrapper来处理

//Map等值判断查询,且Map只能做等值判断,逻辑判断需要使用Wrapper来处理
Map<String,Object> map = new HashMap<>();
map.put("id",3);
mapper.selectByMap(map);

(15)、查询相关数量,比如说id大于1的

//查询相关数量,比如说id大于1的
wrapper.gt("id",1);
mapper.selectCount(wrapper);

(16)、将查询结果集封装到Map中

//将查询的结果集封装到Map中,下面两个虽说返回的结果一样,但是返回的形式不一样
QueryWrapper wrapper = new QueryWrapper();
wrapper.gt("id",1);
//以map集合的形式返回
mapper.selectMaps(wrapper).forEach(System.out::println);
//以对象的形式返回
mapper.selectList(wrapper).forEach(System.out::println);

(17)、查询单个数据

//查询单个数据
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("id",1);
mapper.selectOne(wrapper);

2)、分页查询

(1)、基本分页查询

//分页查询
Page<User> page = new Page<>(1,5);
Page<User> result = mapper.selectPage(page,null);
System.out.println(result.getSize());//返回的页数
System.out.println(result.getTotal());//返回的页的数量
result.getRecords().forEach(System.out::println);

(2)、分页查询,以map集合的形式返回

//分页查询
Page<Map<String,Object>> page = new Page<>(1,5);
mapper.selectMapsPage(page,null).getRecords();

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

(1)、定义实体类

package com.exerciseitems.mybatisplus.entity;

import lombok.Data;

/**
 * @author : [LiuYanQiang]
 * @version : [v1.0]
 * @className : ProductVO
 * @description : [描述说明该类的功能]
 * @createTime : [2021/9/15 16:54]
 * @updateUser : [LiuYanQiang]
 * @updateTime : [2021/9/15 16:54]
 * @updateRemark : [描述说明本次修改内容]
 */
@Data
public class ProductVO {
    private Integer category;
    private Integer count;
    private String description;
    private Integer userId;
    private String userName;
}

(2)、自定义SQL查询

package com.exerciseitems.mybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.exerciseitems.mybatisplus.entity.ProductVO;
import com.exerciseitems.mybatisplus.entity.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * @author : [LiuYanQiang]
 * @version : [v1.0]
 * @className : UserMapper
 * @description : [描述说明该类的功能]
 * @createTime : [2021/9/15 17:26]
 * @updateUser : [LiuYanQiang]
 * @updateTime : [2021/9/15 17:26]
 * @updateRemark : [描述说明本次修改内容]
 */
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);
}

猜你喜欢

转载自blog.csdn.net/weixin_44684272/article/details/120367350