SpringBoot + Mybatis Plus + Oracle 主键自增的配置

 

由于 Oracle 不像 SQL Server 和 MySQL 有主键自增的设计,需要用创建序列或者触发器的方式实现主键增长,使用 Mybatis 时可以直接在 SQL 语句中使用序列,如果我们使用 Mybatis Plus 的通用 Mapper ,不自己写 SQL,这种情况下要实现主键自增就需要做一些额外的配置了:

 

1. 在application.yml 配置文件中增加

mybatis-plus:
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 1
    # Sequence序列接口实现类配置
    key-generator: com.baomidou.mybatisplus.incrementer.OracleKeyGenerator

其中 id-type 值为1 表示 “用户输入ID”,使用序列就相当于用户输入ID 

2. 实体类增加 @KeySequence 注解,@TableId 增加 type = IdType.INPUT

@Data
@Accessors(chain = true)
@TableName("yjk_user")
@KeySequence(value = "SEQ_YJK_USER", clazz = Integer.class)
public class User extends Model<User> {

    private static final long serialVersionUID = 1L;

    @TableId(value = "user_id", type = IdType.INPUT)
    private Integer userId;

    @TableField("phone_number")
    private String phoneNumber;

    @TableField("password")
    private String password;

}

其中 @KeySequence 注解中的 value 值为你创建的对应这张表的序列名,clazz 的值是和表的主键类型对应的,如果表的主键是varchar2 类型但是需要从 sequence 中取值,可以直接将 clazz 的值设为 String.class

还要注意 type = Idtype.Input 一定不能用 type = Idtype.Auto

发布了119 篇原创文章 · 获赞 24 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/zhang33565417/article/details/104068032