我是靠谱客的博主 儒雅鲜花,这篇文章主要介绍mybatis plus常见用法(分页查询、字段自动填充策略、自定义Id生成器、逻辑删除),现在分享给大家,希望可以做个参考。

1、mybatis plus分页查询的使用;

目录

1、mybatis plus分页查询的使用;

2、TableField字段自动填充策略的使用

3、自定义id生成器的使用

ASSIGN_ID

声明为 Bean 供 Spring 扫描注入

 4、逻辑删除的使用

步骤 1: 配置com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig

步骤 2: 实体类字段上加上@TableLogic注解


官网文档CRUD 接口 | MyBatis-Plus

复制代码
1
2
3
4
5
6
7
8
// 无条件分页查询 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);

pom文件中引入依赖

复制代码
1
2
3
4
5
6
<!-- mybatis_plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.2</version> </dependency>

分页插件配置:

复制代码
1
2
3
4
5
6
7
8
9
@Configuration public class MybatisConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }

TbOrderInfo实体类

复制代码
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
@Data @AllArgsConstructor @NoArgsConstructor @ToString @TableName("tb_order_info") public class TbOrderInfo { @TableId(value = "order_id", type = IdType.ASSIGN_ID) private Long orderId; private String userId; private String userAccount; private String orderNo; // @TableField(fill = FieldFill.INSERT) private String submitTime; private double actualPaidPrice; private long orderStatus; private String payWay; // @TableField(update = "now") private String receiptAddress; @TableLogic private Integer flag; }

dao层mapper文件

复制代码
1
2
3
4
5
@Mapper @Repository public interface OrderInfoMapper extends BaseMapper<TbOrderInfo> { }

service接口及实现类

复制代码
1
2
3
public interface OrderInfoService extends IService<TbOrderInfo> { }
复制代码
1
2
3
4
5
@Service @Slf4j public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, TbOrderInfo> implements OrderInfoService { }

Controller层中使用分页查询

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RestController @Slf4j public class OrderInfoController { @Autowired private OrderInfoService orderInfoService; //分页查询 @GetMapping("/testPageQuery") public Result queryPage(){ QueryWrapper<TbOrderInfo> wrapper = new QueryWrapper<>(); // wrapper.eq("actual_paid_price", 0); Page<TbOrderInfo> page = orderInfoService.page(new Page<>(1, 3, 3, true), wrapper); return ResultUtil.success(page); } }

2、TableField字段自动填充策略的使用

框架代码源码:

复制代码
1
2
3
4
5
6
7
8
9
public enum FieldFill { DEFAULT, INSERT, UPDATE, INSERT_UPDATE; private FieldFill() { } }

自动填充配置文件:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
@Component public class MyMetaObjectHandler implements MetaObjectHandler { //执行插入操作时,默认填充属性值 @Override public void insertFill(MetaObject metaObject) { this.setFieldValByName("submitTime", new Date().toString(), metaObject); } //执行更新操作时,默认填充属性值 @Override public void updateFill(MetaObject metaObject) { } }

实体类中给对应的字段加上注解

复制代码
1
@TableField(fill = FieldFill.INSERT)

3、自定义id生成器的使用

mybatis plus支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题

复制代码
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
/* * Copyright (c) 2011-2022, baomidou (jobob@qq.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.baomidou.mybatisplus.annotation; import lombok.Getter; /** * 生成ID类型枚举类 * * @author hubin * @since 2015-11-10 */ @Getter public enum IdType { /** * 数据库ID自增 * <p>该类型请确保数据库设置了 ID自增 否则无效</p> */ AUTO(0), /** * 该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT) */ NONE(1), /** * 用户输入ID * <p>该类型可以通过自己注册自动填充插件进行填充</p> */ INPUT(2), /* 以下2种类型、只有当插入对象ID 为空,才自动填充。 */ /** * 分配ID (主键类型为number或string), * 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(雪花算法) * * @since 3.3.0 */ ASSIGN_ID(3), /** * 分配UUID (主键类型为 string) * 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(UUID.replace("-","")) */ ASSIGN_UUID(4); private final int key; IdType(int key) { this.key = key; } }

这里以assign_id为例

ASSIGN_ID

分配ID (主键类型为number或string),默认实现类 DefaultIdentifierGenerator(雪花算法)。

方式一使用默认生成器

  1. 取消数据库表ID自增
  2. 设置实体类IdType为ASSIGN_ID,字段类型为Long

配置文件中配置id-type: assign_id

复制代码
1
2
3
4
5
6
7
8
9
# mybatis-plus相关配置 mybatis-plus: # xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置) mapper-locations: classpath:mapper/*.xml configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: db-config: id-type: assign_id

声明为 Bean 供 Spring 扫描注入

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Component public class CustomIdGenerator implements IdentifierGenerator { @Override public Long nextId(Object entity) { //可以将当前传入的class全类名来作为bizKey,或者提取参数来生成bizKey进行分布式Id调用生成. String bizKey = entity.getClass().getName(); //根据bizKey调用分布式ID生成 // long id = ....; //返回生成的id值即可. //使用 hutools 雪花算法生成分布式ID //参数1为终端ID //参数2为数据中心ID Snowflake snowflake = IdUtil.getSnowflake(1, 1); return snowflake.nextId(); } }

实体类中配置主键

复制代码
1
@TableId(value = "order_id", type = IdType.ASSIGN_ID)

 4、逻辑删除的使用

官网说明及配置:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
说明: 只对自动注入的 sql 起效: 插入: 不作限制 查找: 追加 where 条件过滤掉已删除数据,如果使用 wrapper.entity 生成的 where 条件也会自动追加该字段 更新: 追加 where 条件防止更新到已删除数据,如果使用 wrapper.entity 生成的 where 条件也会自动追加该字段 删除: 转变为 更新 例如: 删除: update user set deleted=1 where id = 1 and deleted=0 查找: select id,name,deleted from user where deleted=0 字段类型支持说明: 支持所有数据类型(推荐使用 Integer,Boolean,LocalDateTime) 如果数据库字段使用datetime,逻辑未删除值和已删除值支持配置为字符串null,另一个值支持配置为函数来获取值如now() 附录: 逻辑删除是为了方便数据恢复和保护数据本身价值等等的一种方案,但实际就是删除。 如果你需要频繁查出来看就不应使用逻辑删除,而是以一个状态去表示。

步骤 1: 配置com.baomidou.mybatisplus.core.config.GlobalConfig$DbConfig

application.yml中配置

复制代码
1
2
3
4
5
6
mybatis-plus: global-config: db-config: logic-delete-field: flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2) logic-delete-value: 1 # 逻辑已删除值(默认为 1) logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

步骤 2: 实体类字段上加上@TableLogic注解

复制代码
1
2
@TableLogic private Integer flag;

以上配置完成之后,执行删除操作时,不再会直接删除数据库中的数据,而是会使用逻辑删除将字段值从0更新为1,执行查询操作时也之后查询出逻辑删除字段值为0的数据;

最后

以上就是儒雅鲜花最近收集整理的关于mybatis plus常见用法(分页查询、字段自动填充策略、自定义Id生成器、逻辑删除)的全部内容,更多相关mybatis内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(90)

评论列表共有 0 条评论

立即
投稿
返回
顶部