本小节是使用此插件最常使用的功能,不难了解即可,本章内容也可当做字典来查问
一、AbstractWrapper
QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper) 的父类,用于生成 sql 的 where 条件, entity 属性也用于生成 sql 的 where 条件,注意: entity 生成的 where 条件与 使用各个 api 生成的 where 条件没有任何关联行为
QueryWrapper
继承自 AbstractWrapper ,自身的内部属性 entity 也用于生成 where 条件,及 LambdaQueryWrapper, 可以通过 new QueryWrapper().lambda() 方法获取
select(String... sqlSelect)
select(Predicate<TableFieldInfo> predicate)
select(Class<T> entityClass, Predicate<TableFieldInfo> predicate)所有方法如下表所示:
方法名  | 说明  | 使用  | 
allEq(Map<R, V> params)  | 全部 =(或个别 isNull)  | allEq(params,true)  | 
eq  | =  | eq(“real_name”,“王昭君”)  | 
ne  | <>  | ne(“nick_name”,“空想 4”)  | 
gt  | >  | gt(“age”,21)  | 
ge  | >=  | ge(“age”,22)  | 
lt  | <  | lt(“age”,22)  | 
le  | <=  | le(“age”,21")  | 
between  | cloum between ? and ?  | between(“age”,0,21)  | 
notBetween  | cloum between ? and ?  | notBetween(“age”,0,21)  | 
like  | cloum like ‘% 王 %’  | like(“real_name”,“王”)  | 
notLike  | not like ‘% 王 %’  | notLike(“real_name”,“王”)  | 
likeLeft  | like ‘% 王’  | likeLeft(“real_name”,“昭”)  | 
likeRight  | like ‘王 %’  | likeRight(“real_name”,“昭”)  | 
isNull  | is null  | isNull(“gender”)  | 
isNotNull  | is not null  | isNotNull(“gender”)  | 
in  | in (1,2,3)  | in(“nick_name”,lists)  | 
notIn  | age not in (1,2,3)  | notIn(“nick_name”,lists)  | 
inSql  | age in (1,2,3,4,5,6)  | inSql(“nick_name”,"‘空想 4’,‘空想 5’,‘空想 6’")  | 
notInSql  | age not in (1,2,3,4,5,6)  | notInSql(“nick_name”,"‘空想 4’,‘空想 5’,‘空想 6’")  | 
groupBy  | group by id,name  | groupBy(“nick_name”,“age”)  | 
orderByAsc  | order by id ASC,name ASC  | orderByAsc(“nick_name”,“age”)  | 
orderByDesc  | order by id DESC,name DESC  | orderByDesc(“age”)  | 
orderBy  | order by id ASC,name ASC  | orderBy(true,true,“age”)  | 
having  | having sum(age) > 10  | having(“sum(age) > 10”)  | 
or  | id = 1 or name = ‘老王’  | eq(“nick_name”,“空想 4”).or(i->i.eq(“age”,21) eq(“nick_name”,“空想 4”).or().eq(“nick_name”,“空想 5”)  | 
and  | and (name = ‘李白’ and status <> ‘活着’)  | and(i->i.eq(“age”,21))  | 
nested  | (name = ‘李白’ and status <> ‘活着’)  | nested(i->i.eq(“age”,21).eq(“nick_name”,“空想 4”))  | 
apply  | id = 1  | apply(“nick_name = ‘空想 4’”)  | 
last  | 最后添加多个以最后的为准,有 sql 注入风险  | last(“limit 1”)  | 
exists  | 拼接 EXISTS (sql 语句)  | exists(“select id from table where age = 1”)  | 
notExists  | 拼接 NOT EXISTS (sql 语句)  | notExists(“select id from table where age = 1”)  | 
UpdateWrapper
继承自 AbstractWrapper ,自身的内部属性 entity 也用于生成 where 条件及 LambdaUpdateWrapper, 可以通过 new UpdateWrapper().lambda() 方法获取!
set(String column, Object val)
set(boolean condition, String column, Object val)public class UpdateWrapperTest {
    
    private UserMapper userMapper;
    /**
     * UPDATE user SET age=?, email=? WHERE (name = ?)
     */
    
    public void tests() {
        //方式一:
        User user = new User();
        user.setAge(29);
        user.setEmail("test3update@baomidou.com");
        userMapper.update(user,new UpdateWrapper<User>().eq("name","Tom"));
        //方式二:
        //不创建User对象
        userMapper.update(null,new UpdateWrapper<User>()
                .set("age",29).set("email","test3update@baomidou.com").eq("name","Tom"));
    }
    /**
     * 使用lambda条件构造器
     * UPDATE user SET age=?, email=? WHERE (name = ?)
     */
    
    public void testLambda() {
        //方式一:
        User user = new User();
        user.setAge(29);
        user.setEmail("test3update@baomidou.com");
        userMapper.update(user,new LambdaUpdateWrapper<User>().eq(User::getName,"Tom"));
        //方式二:
        //不创建User对象
        userMapper.update(null,new LambdaUpdateWrapper<User>()
                .set(User::getAge,29).set(User::getEmail,"test3update@baomidou.com").eq(User::getName,"Tom"));
    }
}二、操作接口
IService CRUD 接口
- 泛型 T 为任意实体对象
 - 对象 Wrapper 为 条件构造器
 
Save
// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);参数说明
类型  | 参数名  | 描述  | 
T  | entity  | 实体对象  | 
Collection<T>  | entityList  | 实体对象集合  | 
int  | batchSize  | 插入批次数量  | 
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);参数说明
类型  | 参数名  | 描述  | 
T  | entity  | 实体对象  | 
Wrapper<T>  | updateWrapper  | 实体对象封装操作类 UpdateWrapper  | 
Collection<T>  | entityList  | 实体对象集合  | 
int  | batchSize  | 插入批次数量  | 
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);
参数说明
类型  | 参数名  | 描述  | 
Wrapper<T>  | queryWrapper  | 实体包装类 QueryWrapper  | 
Serializable  | id  | 主键 ID  | 
Map<String, Object>  | columnMap  | 表字段 map 对象  | 
Collection<? extends Serializable>  | idList  | 主键 ID 列表  | 
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);参数说明
类型  | 参数名  | 描述  | 
Wrapper<T>  | updateWrapper  | 实体对象封装操作类 UpdateWrapper  | 
T  | entity  | 实体对象  | 
Collection<T>  | entityList  | 实体对象集合  | 
int  | batchSize  | 更新批次数量  | 
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);参数说明
类型  | 参数名  | 描述  | 
Serializable  | id  | 主键 ID  | 
Wrapper<T>  | queryWrapper  | 实体对象封装操作类 QueryWrapper  | 
boolean  | throwEx  | 有多个 result 是否抛出异常  | 
T  | entity  | 实体对象  | 
Function<? super Object, V>  | mapper  | 转换函数  | 
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);参数说明
类型  | 参数名  | 描述  | 
Wrapper<T>  | queryWrapper  | 实体对象封装操作类 QueryWrapper  | 
Collection<? extends Serializable>  | idList  | 主键 ID 列表  | 
Map<String, Object>  | columnMap  | 表字段 map 对象  | 
Function<? super Object, V>  | mapper  | 转换函数  | 
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);参数说明
类型  | 参数名  | 描述  | 
IPage<T>  | page  | 翻页对象  | 
Wrapper<T>  | queryWrapper  | 实体对象封装操作类 QueryWrapper  | 
Count
// 查询总记录数
int count();
// 根据 Wrapper 条件,查询总记录数
int count(Wrapper<T> queryWrapper);参数说明
类型  | 参数名  | 描述  | 
Wrapper<T>  | queryWrapper  | 实体对象封装操作类 QueryWrapper  | 
LambdaChain
query
// 链式查询 普通
QueryChainWrapper<T> query();
// 链式查询 lambda 式。注意:不支持 Kotlin
LambdaQueryChainWrapper<T> lambdaQuery();
// 示例:
query().eq("column", value).one();
lambdaQuery().eq(Entity::getId, value).list();update
// 链式更改 普通
UpdateChainWrapper<T> update();
// 链式更改 lambda 式。注意:不支持 Kotlin
LambdaUpdateChainWrapper<T> lambdaUpdate();
// 示例:
update().eq("column", value).remove();
lambdaUpdate().eq(Entity::getId, value).update(entity);BaseMapper CRUD 接口
通用 CRUD 封装BaseMapper (opens new window)接口,为 Mybatis-Plus 启动时自动解析实体表关系映射转换为 Mybatis 内部对象注入容器
- 泛型 T 为任意实体对象
 - 参数 Serializable 为任意类型主键 Mybatis-Plus 不推荐使用复合主键约定每一张表都有自己的唯一 id 主键
 - 对象 Wrapper 为 条件构造器
 
insert
// 插入一条记录
int insert(T entity);参数说明
类型  | 参数名  | 描述  | 
T  | entity  | 实体对象  | 
Delete
// 根据 entity 条件,删除记录
int delete((Constants.WRAPPER) Wrapper<T> wrapper);
// 删除(根据ID 批量删除)
int deleteBatchIds((Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 ID 删除
int deleteById(Serializable id);
// 根据 columnMap 条件,删除记录
int deleteByMap((Constants.COLUMN_MAP) Map<String, Object> columnMap);参数说明
类型  | 参数名  | 描述  | 
Wrapper<T>  | wrapper  | 实体对象封装操作类(可以为 null)  | 
Collection<? extends Serializable>  | idList  | 主键 ID 列表(不能为 null 以及 empty)  | 
Serializable  | id  | 主键 ID  | 
Map<String, Object>  | columnMap  | 表字段 map 对象  | 
Update
// 根据 whereWrapper 条件,更新记录
int update((Constants.ENTITY) T updateEntity, (Constants.WRAPPER) Wrapper<T> whereWrapper);
// 根据 ID 修改
int updateById((Constants.ENTITY) T entity);
参数说明
类型  | 参数名  | 描述  | 
T  | entity  | 实体对象 (set 条件值,可为 null)  | 
Wrapper<T>  | updateWrapper  | 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)  | 
Select
// 根据 ID 查询
T selectById(Serializable id);
// 根据 entity 条件,查询一条记录
T selectOne((Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据ID 批量查询)
List<T> selectBatchIds((Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 entity 条件,查询全部记录
List<T> selectList((Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据 columnMap 条件)
List<T> selectByMap((Constants.COLUMN_MAP) Map<String, Object> columnMap);
// 根据 Wrapper 条件,查询全部记录
List<Map<String, Object>> selectMaps((Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
List<Object> selectObjs((Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 entity 条件,查询全部记录(并翻页)
IPage<T> selectPage(IPage<T> page, (Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录(并翻页)
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, (Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询总记录数
Integer selectCount((Constants.WRAPPER) Wrapper<T> queryWrapper);参数说明
类型  | 参数名  | 描述  | 
Serializable  | id  | 主键 ID  | 
Wrapper<T>  | queryWrapper  | 实体对象封装操作类(可以为 null)  | 
Collection<? extends Serializable>  | idList  | 主键 ID 列表(不能为 null 以及 empty)  | 
Map<String, Object>  | columnMap  | 表字段 map 对象  | 
IPage<T>  | page  | 分页查询条件(可以为 RowBounds.DEFAULT)  | 
三、分页插件
集成方式-spring
<!-- spring xml 方式 -->
<property name="plugins">
    <array>
        <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor">
            <property name="sqlParser" ref="自定义解析类、可以没有"/>
            <property name="dialectClazz" value="自定义方言类、可以没有"/>
            <!-- COUNT SQL 解析.可以没有 -->
            <property name="countSqlParser" ref="countSqlParser"/>
        </bean>
    </array>
</property>
<bean id="countSqlParser" class="com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize">
    <!-- 设置为 true 可以优化部分 left join 的sql -->
    <property name="optimizeJoin" value="true"/>
</bean>集成方式-springboot
//Spring boot方式
public class MybatisPlusConfig {
    // 最新版
    
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }
}代码实现
配置实现
public interface UserMapper {//可以继承或者不继承BaseMapper
    /**
     * <p>
     * 查询 : 根据state状态查询用户列表,分页显示
     * </p>
     *
     * @param page 分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位(你可以继承Page实现自己的分页对象)
     * @param state 状态
     * @return 分页对象
     */
    IPage<User> selectPageVo(Page<?> page, Integer state);//这处可以不写@param
}--------------------------------------mapper.xml--------------------------------------------
<select id="selectPageVo" resultType="com.baomidou.cloud.entity.UserVo">
    SELECT id,name FROM user WHERE state=#{state}
</select>编码实现
public IPage<User> selectUserPage(Page<User> page, Integer state) {
    // 不进行 count sql 优化,解决 MP 无法自动优化 SQL 问题,这时候你需要自己查询 count 部分
    // page.setOptimizeCountSql(false);
    // 当 total 为小于 0 或者设置 setSearchCount(false) 分页插件不会进行 count 查询
    // 要点!! 分页返回的对象与传入的对象是同一个
    return userMapper.selectPageVo(page, state);
}-----------------------------UserServiceImpl.java 调用分页方法-----------------------------------
public IPage<CaseEntity> pageCaseByCondition(Integer page, Integer size, CaseQuery caseQuery) {
        //设置查询条件
        QueryWrapper<CaseEntity> querySql = new QueryWrapper<>();
        //querySql.orderByDesc("ctime");
        //querySql.like("column", "");
        IPage<CaseEntity> iPage = new Page<>(page, size); //IPage<CaseEntity> patientPage1 = new Page<>(page, size, false);//不查询总页数
        IPage<CaseEntity> result = this.getBaseMapper().selectPage(iPage, querySql);
//        System.out.println("总页数: "+result.getPages());
//       System.out.println("总记录数: "+result.getTotal());
        return result;
    }









