一、新建一个序列
-- Create sequence seq_app_user_id为序列名,自行修改
create sequence seq_app_user_id
minvalue 1
maxvalue 9999999
start with 1
increment by 1
cache 20;
也可通过客户端工具直接创建,如图
二、通过使用@SequenceGenerator和@GeneratedValue实现自增
@Entity
@Data
@SequenceGenerator(name = "appUserId",sequenceName = "seq_app_user_id",allocationSize = 1)
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "appUserId")
private Integer id;
private String name;
private LocalDate registerDate;
private LocalDateTime createTime;
}
三、注意事项
1、@SequenceGenerator
- name 自定义即可
- sequenceName 第一步中新建的序列名字
- allocationSize 增量,和建立的序列增量保持一致
2、@GeneratedValue
- strategy = GenerationType.SEQUENCE
- generator 和@SequenceGenerator中的name一致