mybatisplus怎么设置自增
时间: 2023-10-10 10:04:29 浏览: 121
Mybatis-Plus可以通过使用@Version注解来实现字段自增。首先,需要在需要自增的字段上添加@Version注解。例如,在readCount字段上添加@Version注解:@Version private Integer readCount;接下来,需要实例化OptimisticLockerInnerInterceptor,并将其添加到MyBatis-Plus的拦截器链中。可以通过如下方式实现:
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mybatisPlusInterceptor;
}
通过以上步骤,就可以实现Mybatis-Plus的字段自增功能。
相关问题
mybatisplus id自增
在MyBatis-Plus中,可以通过使用注解@TableId和@TableName来实现自增长ID。其中@TableId注解用于标识主键字段,@TableName注解用于标识表名。在@TableId注解中,可以设置value属性为Id字段名,type属性为Id类型,如下所示:
```java
@TableId(value = "id", type = IdType.AUTO)
private Long id;
```
其中,type属性有以下几种取值:
- AUTO:数据库ID自增
- NONE:无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
- INPUT:用户输入ID,该类型可以通过自己注册自动填充插件进行填充(注解里等于跟随全局,全局里约等于 ID_WORKER)
- ID_WORKER:全局唯一ID,Long类型的数字类型,生成策略为:ID_WORKER,1L
- UUID:全局唯一ID,String类型,生成策略为:UUID
- ID_WORKER_STR:字符串全局唯一ID,生成策略为:ID_WORKER,该类型可以通过自己注册自动填充插件进行填充
例如,使用AUTO类型自增长ID的示例代码如下:
```java
@TableId(value = "id", type = IdType.AUTO)
private Long id;
```
mybatisplus主键自增
MyBatis-Plus(简称MP)是一款基于 MyBatis 的增强工具,它提供了许多便捷的功能,包括主键自增。
在 MyBatis-Plus 中,实现主键自增有两种方式:
1. 使用数据库的自增主键策略:在数据库表中设置主键字段为自增,在实体类中将该字段标记为 `@TableId(type = IdType.AUTO)`,这样在插入数据时,数据库会自动生成主键值并返回给实体对象。
示例代码:
```java
@Data
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String username;
private String password;
}
```
2. 使用雪花算法生成全局唯一的主键值:在实体类中将主键字段标记为 `@TableId(type = IdType.ASSIGN_ID)`,这样在插入数据时,MyBatis-Plus 会使用雪花算法生成唯一的主键值。
示例代码:
```java
@Data
@TableName("user")
public class User {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private String username;
private String password;
}
```
以上就是 MyBatis-Plus 中实现主键自增的两种方式。你可以根据需求选择合适的方式来使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)