• mybatisPlus笔记


    MybatisPlus重要知识点


    官网文档

    代码地址

    1、基本CRUD

    1.1、继承BaseMapper

    BaseMapper类如下所示:

    public interface BaseMapper<T> extends Mapper<T> {
    
        /**
         * 插入一条记录
         *
         * @param entity 实体对象
         */
        int insert(T entity);
    
        /**
         * 根据 ID 删除
         *
         * @param id 主键ID
         */
        int deleteById(Serializable id);
    
        /**
         * 根据 columnMap 条件,删除记录
         *
         * @param columnMap 表字段 map 对象
         */
        int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
    
        /**
         * 根据 entity 条件,删除记录
         *
         * @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
         */
        int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
    
        /**
         * 删除(根据ID 批量删除)
         *
         * @param idList 主键ID列表(不能为 null 以及 empty)
         */
        int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
    
        /**
         * 根据 ID 修改
         *
         * @param entity 实体对象
         */
        int updateById(@Param(Constants.ENTITY) T entity);
    
        /**
         * 根据 whereEntity 条件,更新记录
         *
         * @param entity        实体对象 (set 条件值,可以为 null)
         * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
         */
        int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
    
        /**
         * 根据 ID 查询
         *
         * @param id 主键ID
         */
        T selectById(Serializable id);
    
        /**
         * 查询(根据ID 批量查询)
         *
         * @param idList 主键ID列表(不能为 null 以及 empty)
         */
        List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
    
        /**
         * 查询(根据 columnMap 条件)
         *
         * @param columnMap 表字段 map 对象
         */
        List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
    
        /**
         * 根据 entity 条件,查询一条记录
         *
         * @param queryWrapper 实体对象封装操作类(可以为 null)
         */
        T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
    
        /**
         * 根据 Wrapper 条件,查询总记录数
         *
         * @param queryWrapper 实体对象封装操作类(可以为 null)
         */
        Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
    
        /**
         * 根据 entity 条件,查询全部记录
         *
         * @param queryWrapper 实体对象封装操作类(可以为 null)
         */
        List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
    
        /**
         * 根据 Wrapper 条件,查询全部记录
         *
         * @param queryWrapper 实体对象封装操作类(可以为 null)
         */
        List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
    
        /**
         * 根据 Wrapper 条件,查询全部记录
         * 

    注意: 只返回第一个字段的值

    * * @param queryWrapper 实体对象封装操作类(可以为 null) */
    List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 entity 条件,查询全部记录(并翻页) * * @param page 分页查询条件(可以为 RowBounds.DEFAULT) * @param queryWrapper 实体对象封装操作类(可以为 null) */ <E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); /** * 根据 Wrapper 条件,查询全部记录(并翻页) * * @param page 分页查询条件 * @param queryWrapper 实体对象封装操作类 */ <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper); }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126

    1.2、继承IService

    public interface IService<T> {
    
        /**
         * 默认批次提交数量
         */
        int DEFAULT_BATCH_SIZE = 1000;
    
        /**
         * 插入一条记录(选择字段,策略插入)
         *
         * @param entity 实体对象
         */
        default boolean save(T entity) {
            return SqlHelper.retBool(getBaseMapper().insert(entity));
        }
    
        /**
         * 插入(批量)
         *
         * @param entityList 实体对象集合
         */
        @Transactional(rollbackFor = Exception.class)
        default boolean saveBatch(Collection<T> entityList) {
            return saveBatch(entityList, DEFAULT_BATCH_SIZE);
        }
    
        /**
         * 插入(批量)
         *
         * @param entityList 实体对象集合
         * @param batchSize  插入批次数量
         */
        boolean saveBatch(Collection<T> entityList, int batchSize);
    
        /**
         * 批量修改插入
         *
         * @param entityList 实体对象集合
         */
        @Transactional(rollbackFor = Exception.class)
        default boolean saveOrUpdateBatch(Collection<T> entityList) {
            return saveOrUpdateBatch(entityList, DEFAULT_BATCH_SIZE);
        }
    
        /**
         * 批量修改插入
         *
         * @param entityList 实体对象集合
         * @param batchSize  每次的数量
         */
        boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
    
        /**
         * 根据 ID 删除
         *
         * @param id 主键ID
         */
        default boolean removeById(Serializable id) {
            return SqlHelper.retBool(getBaseMapper().deleteById(id));
        }
    
        /**
         * 根据 columnMap 条件,删除记录
         *
         * @param columnMap 表字段 map 对象
         */
        default boolean removeByMap(Map<String, Object> columnMap) {
            Assert.notEmpty(columnMap, "error: columnMap must not be empty");
            return SqlHelper.retBool(getBaseMapper().deleteByMap(columnMap));
        }
    
        /**
         * 根据 entity 条件,删除记录
         *
         * @param queryWrapper 实体包装类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper}
         */
        default boolean remove(Wrapper<T> queryWrapper) {
            return SqlHelper.retBool(getBaseMapper().delete(queryWrapper));
        }
    
        /**
         * 删除(根据ID 批量删除)
         *
         * @param idList 主键ID列表
         */
        default boolean removeByIds(Collection<? extends Serializable> idList) {
            if (CollectionUtils.isEmpty(idList)) {
                return false;
            }
            return SqlHelper.retBool(getBaseMapper().deleteBatchIds(idList));
        }
    
        /**
         * 根据 ID 选择修改
         *
         * @param entity 实体对象
         */
        default boolean updateById(T entity) {
            return SqlHelper.retBool(getBaseMapper().updateById(entity));
        }
    
        /**
         * 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
         *
         * @param updateWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper}
         */
        default boolean update(Wrapper<T> updateWrapper) {
            return update(null, updateWrapper);
        }
    
        /**
         * 根据 whereEntity 条件,更新记录
         *
         * @param entity        实体对象
         * @param updateWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper}
         */
        default boolean update(T entity, Wrapper<T> updateWrapper) {
            return SqlHelper.retBool(getBaseMapper().update(entity, updateWrapper));
        }
    
        /**
         * 根据ID 批量更新
         *
         * @param entityList 实体对象集合
         */
        @Transactional(rollbackFor = Exception.class)
        default boolean updateBatchById(Collection<T> entityList) {
            return updateBatchById(entityList, DEFAULT_BATCH_SIZE);
        }
    
        /**
         * 根据ID 批量更新
         *
         * @param entityList 实体对象集合
         * @param batchSize  更新批次数量
         */
        boolean updateBatchById(Collection<T> entityList, int batchSize);
    
        /**
         * TableId 注解存在更新记录,否插入一条记录
         *
         * @param entity 实体对象
         */
        boolean saveOrUpdate(T entity);
    
        /**
         * 根据 ID 查询
         *
         * @param id 主键ID
         */
        default T getById(Serializable id) {
            return getBaseMapper().selectById(id);
        }
    
        /**
         * 查询(根据ID 批量查询)
         *
         * @param idList 主键ID列表
         */
        default List<T> listByIds(Collection<? extends Serializable> idList) {
            return getBaseMapper().selectBatchIds(idList);
        }
    
        /**
         * 查询(根据 columnMap 条件)
         *
         * @param columnMap 表字段 map 对象
         */
        default List<T> listByMap(Map<String, Object> columnMap) {
            return getBaseMapper().selectByMap(columnMap);
        }
    
        /**
         * 根据 Wrapper,查询一条记录 
    *

    结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")

    * * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper} */
    default T getOne(Wrapper<T> queryWrapper) { return getOne(queryWrapper, true); } /** * 根据 Wrapper,查询一条记录 * * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper} * @param throwEx 有多个 result 是否抛出异常 */ T getOne(Wrapper<T> queryWrapper, boolean throwEx); /** * 根据 Wrapper,查询一条记录 * * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper} */ Map<String, Object> getMap(Wrapper<T> queryWrapper); /** * 根据 Wrapper,查询一条记录 * * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper} * @param mapper 转换函数 */ <V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper); /** * 查询总记录数 * * @see Wrappers#emptyWrapper() */ default int count() { return count(Wrappers.emptyWrapper()); } /** * 根据 Wrapper 条件,查询总记录数 * * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper} */ default int count(Wrapper<T> queryWrapper) { return SqlHelper.retCount(getBaseMapper().selectCount(queryWrapper)); } /** * 查询列表 * * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper} */ default List<T> list(Wrapper<T> queryWrapper) { return getBaseMapper().selectList(queryWrapper); } /** * 查询所有 * * @see Wrappers#emptyWrapper() */ default List<T> list() { return list(Wrappers.emptyWrapper()); } /** * 翻页查询 * * @param page 翻页对象 * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper} */ default <E extends IPage<T>> E page(E page, Wrapper<T> queryWrapper) { return getBaseMapper().selectPage(page, queryWrapper); } /** * 无条件翻页查询 * * @param page 翻页对象 * @see Wrappers#emptyWrapper() */ default <E extends IPage<T>> E page(E page) { return page(page, Wrappers.emptyWrapper()); } /** * 查询列表 * * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper} */ default List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper) { return getBaseMapper().selectMaps(queryWrapper); } /** * 查询所有列表 * * @see Wrappers#emptyWrapper() */ default List<Map<String, Object>> listMaps() { return listMaps(Wrappers.emptyWrapper()); } /** * 查询全部记录 */ default List<Object> listObjs() { return listObjs(Function.identity()); } /** * 查询全部记录 * * @param mapper 转换函数 */ default <V> List<V> listObjs(Function<? super Object, V> mapper) { return listObjs(Wrappers.emptyWrapper(), mapper); } /** * 根据 Wrapper 条件,查询全部记录 * * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper} */ default List<Object> listObjs(Wrapper<T> queryWrapper) { return listObjs(queryWrapper, Function.identity()); } /** * 根据 Wrapper 条件,查询全部记录 * * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper} * @param mapper 转换函数 */ default <V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper) { return getBaseMapper().selectObjs(queryWrapper).stream().filter(Objects::nonNull).map(mapper).collect(Collectors.toList()); } /** * 翻页查询 * * @param page 翻页对象 * @param queryWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.query.QueryWrapper} */ default <E extends IPage<Map<String, Object>>> E pageMaps(E page, Wrapper<T> queryWrapper) { return getBaseMapper().selectMapsPage(page, queryWrapper); } /** * 无条件翻页查询 * * @param page 翻页对象 * @see Wrappers#emptyWrapper() */ default <E extends IPage<Map<String, Object>>> E pageMaps(E page) { return pageMaps(page, Wrappers.emptyWrapper()); } /** * 获取对应 entity 的 BaseMapper * * @return BaseMapper */ BaseMapper<T> getBaseMapper(); /** * 获取 entity 的 class * * @return {@link Class} */ Class<T> getEntityClass(); /** * 以下的方法使用介绍: * * 一. 名称介绍 * 1. 方法名带有 query 的为对数据的查询操作, 方法名带有 update 的为对数据的修改操作 * 2. 方法名带有 lambda 的为内部方法入参 column 支持函数式的 * 二. 支持介绍 * * 1. 方法名带有 query 的支持以 {@link ChainQuery} 内部的方法名结尾进行数据查询操作 * 2. 方法名带有 update 的支持以 {@link ChainUpdate} 内部的方法名为结尾进行数据修改操作 * * 三. 使用示例,只用不带 lambda 的方法各展示一个例子,其他类推 * 1. 根据条件获取一条数据: `query().eq("column", value).one()` * 2. 根据条件删除一条数据: `update().eq("column", value).remove()` * */ /** * 链式查询 普通 * * @return QueryWrapper 的包装类 */ default QueryChainWrapper<T> query() { return ChainWrappers.queryChain(getBaseMapper()); } /** * 链式查询 lambda 式 *

    注意:不支持 Kotlin

    * * @return LambdaQueryWrapper 的包装类 */
    default LambdaQueryChainWrapper<T> lambdaQuery() { return ChainWrappers.lambdaQueryChain(getBaseMapper()); } /** * 链式查询 lambda 式 * kotlin 使用 * * @return KtQueryWrapper 的包装类 */ default KtQueryChainWrapper<T> ktQuery() { return ChainWrappers.ktQueryChain(getBaseMapper(), getEntityClass()); } /** * 链式查询 lambda 式 * kotlin 使用 * * @return KtQueryWrapper 的包装类 */ default KtUpdateChainWrapper<T> ktUpdate() { return ChainWrappers.ktUpdateChain(getBaseMapper(), getEntityClass()); } /** * 链式更改 普通 * * @return UpdateWrapper 的包装类 */ default UpdateChainWrapper<T> update() { return ChainWrappers.updateChain(getBaseMapper()); } /** * 链式更改 lambda 式 *

    注意:不支持 Kotlin

    * * @return LambdaUpdateWrapper 的包装类 */
    default LambdaUpdateChainWrapper<T> lambdaUpdate() { return ChainWrappers.lambdaUpdateChain(getBaseMapper()); } /** *

    * 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法 * 此次修改主要是减少了此项业务代码的代码量(存在性验证之后的saveOrUpdate操作) *

    * * @param entity 实体对象 */
    default boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper) { return update(entity, updateWrapper) || saveOrUpdate(entity); } }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399
    • 400
    • 401
    • 402
    • 403
    • 404
    • 405
    • 406
    • 407
    • 408
    • 409
    • 410
    • 411
    • 412
    • 413
    • 414
    • 415
    • 416
    • 417
    • 418
    • 419
    • 420
    • 421
    • 422
    • 423
    • 424
    • 425
    • 426
    • 427
    • 428
    • 429
    • 430
    • 431
    • 432
    • 433
    • 434
    • 435
    • 436

    两种实现方式。

    2、条件拼接

    上面的两个实例可以看出,需要一个叫Wrapper的属性,该类就是拼接一些参数条件等。

    常用类接口如下所示:

    在这里插入图片描述

    具体的方法不在这儿展示了。

    展示一个使用demo吧

    @SpringBootTest(classes = MybatisPlusStarter.class)
    @RunWith(SpringRunner.class)
    @Slf4j
    public class SampleTest {
    
        @Autowired
        private UserMapper userMapper;
    
        @Autowired
        @Qualifier(value = "userServiceImpl")
        private UserService userService;
    
        @Test
        public void testSelect() {
            System.out.println(("----- selectAll method test ------"));
            List<User> userList = userMapper.selectList(null);
            userList.forEach(System.out::println);
        }
    
        @Test
        public void testInsert() {
            System.out.println(("----- insert method test ------"));
            User user = new User();
            user.setAge(22);
            user.setEmail("1107@qq.com");
            user.setMyName("咸蛋超人");
            int insert = userMapper.insert(user);
            System.out.println("添加了:" + insert + "条数据!");
        }
    
        @Test
        public void testDeleteByMap() {
            Map<String, Object> columnMap = new HashMap<>(2);
            columnMap.put("name", "咸蛋超人");
            columnMap.put("age", "22");
            int result = userMapper.deleteByMap(columnMap);
            System.out.println("受影响行数:" + result);
        }
    
        @Test
        public void testUpdateById() {
            User user = new User(4L, "admin", 22);
    //UPDATE user SET name=?, age=? WHERE id=?
            int result = userMapper.updateById(user);
            System.out.println("受影响行数:" + result);
        }
    
    
        @Test
        public void testServiceByID() {
            User byId = userService.getById(1);
            log.info("输出结果:{}", byId);
        }
    
        @Test
        public void testServiceByWrapper() {
            QueryWrapper<User> wrapper = new QueryWrapper();
            wrapper.like("my_name", "咸蛋%");
            List<User> list = userService.list(wrapper);
            log.info("testServiceByWrapper输出结果:{}", JSONObject.toJSONString(list));
        }
    
    
        @Test
        public void testDelete() {
            List<Integer> idList = new ArrayList<>();
            idList.add(1);
            idList.add(2);
            boolean b = userService.removeByIds(idList);
        }
    
        @Test
        public void testList() {
            List<User> list = userService.list();
            log.info("查询所有:{}", JSONObject.toJSONString(list));
        }
    
        @Test
        public void testQueryWrapper() {
            QueryWrapper<User> wrapper = new QueryWrapper();
            wrapper.select("uid as id", "my_name as myName")
    //                .eq("age", 20)
                    .setEntity(new User())
                    .inSql("uid", "select uid from t_user where uid <= 5");
    /*        wrapper.select(User.class, x -> {
                String property = x.getProperty();
                return property.equals("name");
            }).eq("age", 20);*/
    //        List list = userService.listByIds(Arrays.asList(1,2,3));
            List<User> list = userService.list(wrapper);
            log.info("查询所有:{}", JSONObject.toJSONString(list));
        }
    
        @Test
        public void testUpdateWrapper() {
            UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
            userUpdateWrapper.set("my_name", "迪迦奥特曼")
                    .ge("age", 10)
                    .and(consumer -> {
                        consumer.eq("my_name", "咸蛋超人")
                                .isNotNull("email");
                    });
            boolean update = userService.update(userUpdateWrapper);
            System.out.println(update);
        }
    
        /**
         * 一直报错 说lambda表达式解析失败。
         */
        @Test
        public void testLambdaList() {
            LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.lambdaQuery();
            Predicate<TableFieldInfo> predicate = x -> x.getProperty().equals("myName");
            userLambdaQueryWrapper.select(User.class, predicate).eq(y -> y.getAge(), "20");
            List<User> list = userService.list(userLambdaQueryWrapper);
            log.info("查询所有:{}", JSONObject.toJSONString(list));
        }
    
        @Test
        public void testLambdaCondition() {
            String username = "迪迦奥特曼";
            Integer ageEnd = 30;
            Integer ageBegin = 10;
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper
                    .select(User::getAge, User::getUid, User::getEmail, User::getMyName)
                    .like(StringUtils.isNotBlank(username), User::getMyName, username)
                    .ge(ageBegin != null, User::getAge, ageBegin)
                    .le(ageEnd != null, User::getAge, ageEnd);
            List<User> list = userService.list(queryWrapper);
            log.info("查询所有:{}", JSONObject.toJSONString(list));
        }
    
        @Test
        public void testMyMapperXml() {
            List<User> byId = userMapper.getById(1l);
            log.info("查询所有:{}", JSONObject.toJSONString(byId));
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139

    3、常用注解

    3.1、@TableName()

    • 描述:表名注解,标识实体类对应的表
    • 使用位置:实体类
    属性类型必须指定默认值描述
    valueString“”表名
    schemaString“”schema
    keepGlobalPrefixbooleanfalse是否保持使用全局的 tablePrefix 的值(当全局 tablePrefix 生效时)
    resultMapString“”xml 中 resultMap 的 id(用于满足特定类型的实体类对象绑定)
    autoResultMapbooleanfalse是否自动构建 resultMap 并使用(如果设置 resultMap 则不会进行 resultMap 的自动构建与注入)
    excludePropertyString[]{}需要排除的属性名 @since 3.3.1

    3.2、@TableId

    • 描述:主键注解
    • 使用位置:实体类主键字段
    属性类型必须指定默认值描述
    valueString“”主键字段名
    typeEnumIdType.NONE指定主键类型

    3.3、@TableField()

    • 描述:字段注解(非主键)
    属性类型必须指定默认值描述
    valueString“”数据库字段名
    existbooleantrue是否为数据库表字段

    3.4、@Version

    • 描述:乐观锁注解、标记 @Verison 在字段上

    3.5、@EnumValue

    • 描述:普通枚举类注解(注解在枚举字段上)

    3.6、@TableLogic

    • 描述:表字段逻辑处理注解(逻辑删除)
    属性类型必须指定默认值描述
    valueString“”逻辑未删除值
    delvalString“”逻辑删除值

    4、插件

        @Bean
        public MybatisPlusInterceptor innerInterceptor() {
            MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
            interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));//分页插件
            interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); //乐观锁插件
            return interceptor;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    4.1、分页插件

    • 配置类加入分页插件配置
    • 使用Page类进行分页

    示例:基于自定义xml的形式:

        /**
         * 自定义xml分页查询
         */
        @Test
        public void testMyMapperPageXml() {
            Page<User> userPage = userMapper.selectPageVo(new Page<>(1, 2), 1);
            log.info("分页查询查询所有:{}", JSONObject.toJSONString(userPage));
        }
    
        /**
         *
         * @param page 分页对象,xml中可以从里面进行取值,传递参数 Page 即自动分页,必须放在第一位
         * @param age
         * @return
         */
        Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    示例:基于mybatis plus的实现

    /**
     * mybatis 使用分页插件
     */
    @Test
    public void testSelectByPage() {
        System.out.println(("----- selectAll method test ------"));
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<User>();
        userQueryWrapper.ge("uid", 1);
        IPage iPage = userMapper.selectMapsPage(new Page<>(1, 2), userQueryWrapper);
        List<User> userList = JSONObject.parseArray(JSONObject.toJSONString(iPage.getRecords()), User.class);
        log.info("分页查询返回:{}", JSON.toJSONString(iPage));
        log.info("返回对象:{}", JSON.toJSONString(userList));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    4.2、乐观锁

    • 在乐观锁的字段上添加@Version注解
    • 在配置类中配置乐观锁

    示例:

        @Version
        private Integer version;
    
    调用代码:
        /**
         * mybatis plus 乐观锁插件进行实现,在对应的字段上添加@Version注解
         */
        @Test
        public void mybatisPlusOptimisticLock() {
            Product product = productMapper.selectById(1);
            Product product1 = productMapper.selectById(1);
            product.setPrice(120);
            int update = productMapper.update(product, null);
            System.out.println("第一次修改数据条数为:" + update);
            if (update > 0) {
                product1 = productMapper.selectById(1);
            }
            product1.setPrice(70);
            int update1 = productMapper.update(product1, null);
            System.out.println("第二次修改数据条数为:" + update1);
            Product product3 = productMapper.selectById(1);
            System.out.println(product3);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    4.3、通用枚举类

    • 在枚举类中声明哪个字段保存在数据库
    • 修改配置文件,扫描枚举类的包

    示例: @EnumValue声明哪个字段保存在数据库中

    @Getter
    public enum SexEnum {
        MALE(1, "男"),
        FEMALE(2, "女");
        @EnumValue
        private Integer sex;
        private String sexName;
    
        SexEnum(Integer sex, String sexName) {
            this.sex = sex;
            this.sexName = sexName;
        }
    }
    
    	另一个类引入枚举类即可。
        /**
         * 性别 1男 ;2女
         */
        private SexEnum sex;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
      type-enums-package: com.zgf.study.mybatisplus.enums #枚举类扫描包
    
    • 1

    4.4、自动生成代码

    public class FastAutoGeneratorTest {
        public static void main(String[] args) {
            FastAutoGenerator.create("数据库url", "用户名", "密码")
                .globalConfig(builder -> {
                    builder.author("summit") // 设置作者
                        //.enableSwagger() // 开启 swagger 模式
                        .fileOverride() // 覆盖已生成文件
                        .outputDir("D://mybatis_plus"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent("com.zgf.study") // 设置父包名
                        .moduleName("mybatisplus") // 设置父包模块名
                        .pathInfo(Collections.singletonMap(OutputFile.mapperXml,"D://mybatis_plus"));// 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude("t_user","t_product","payment") // 设置需要生成的表名
                        .addTablePrefix("t_", "c_"); // 设置过滤表前缀
                })
                .templateEngine(new FreemarkerTemplateEngine())
                // 使用Freemarker引擎模板,默认的是Velocity引擎模板
                .execute();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    最后会生成一套代码如下所示:

    在这里插入图片描述

  • 相关阅读:
    vue接入高德地图获取经纬度
    Linux安装oracle 19C
    语法复习之C语言与指针
    (附源码)计算机毕业设计SSM基于框架的旅游管理系统
    内网开发新项目之流程记录
    uniapp输入框组件easyInput初始状态清除符号显示的bug
    六款Linux常用远程连接工具介绍,看看哪一款最适合你
    线程间通信(生产者和消费者案例)
    对象序列化运用
    【20221206】【每日一题】01背包的基础
  • 原文地址:https://blog.csdn.net/zhengguofeng0328/article/details/125898527