您的位置:首页 > 数据库 > Oracle

笔记 oracle 创建主键自增长

2017-05-02 16:51 411 查看

  笔记

  (1) 创建表

  create table test(

    id number(18,2) primary key, -- 主键(unique+not null)

    name varchar2(100) not null

  );

  (2) 创建序列

  create sequence seq_test_id 

  minvalue 1  -- 最小值
  start with 1  -- 起始值
  increment by 1  -- 步长
  nomaxvalue  --没有最大值,若有最大值则需要设置,maxvalue,相对的去掉nomaxvalue
  nocache    -- 不缓存序列,若需要缓存序列的话则改写成cache [number],number为整数,默认为20;

          -- 区别: cache 会在需要用到序列之前先缓存一定数量(默认20个)的序列到内存中,可以提高insert语句性能,但会存在跳号的问题,比如当缓存了20个,还剩5个,突然电脑断电,重启后,它会跳过剩下的5个序列,来取值
  nocycle;    -- 当达到最大值时,不循环使用序列值,循环的话则使用cycle

  (3) 创建触发器

  create or replace trigger trigger_test_id 
  before insert on test for each row when (new.id is null)
  begin
    select seq_test_id.nextval into :new.id from dual;
  end;

  尽管创建触发器很方便,但一般还是用另一种方式:

  hibernate的注解的形式更为方便,快捷,在实体类的主键列上添加注释,4步搞定:

    a. @Id    -- 标注主键列
    b. @Column(name = "id")    -- 标注属性与列的对应关系
    c. @SequenceGenerator(name = "seq_test", sequenceName = "seq_test_id", allocationSize = 1)     -- 标注sequenceName引用数据库中的序列"seq_test_id",并重命名为"seq_test"
    d. @GeneratedValue(generator = "sequence_resume_id", strategy = GenerationType.SEQUENCE)      --- 标注主键生成器和生成策略

  

  

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: