`

Oracle中实现主键自动增长

阅读更多

    现在在看一个别人写的工程,想把它从mysql移植到oracle数据库环境下,mysql中支持主键id自动增长(auto_increment),但是oracle不支持,工程中用的hibernate,在映射多对多关系时使用了中间类,但是并没有实例化中间类,所以保存时中间表的id为空,我很懒,不想改它的代码,所以上网查找并总结了以下方法,可以实现主键自动增长:

    比如我的中间表名为test,实现代码如下:

    1. 创建sequence:

    create sequence test_id increment by 1 start with 1 nocache;

    2. 创建触发器:

    create or replace trigger test_trigger

    before insert on test

    for each row

    begin

        select test_id.nextval into :new.id from dual;

    end;

    /

 

    注意:

        为:new.id取值时不能写成

            :new.id :=test_id.nextval

        这样会报 "PLS-00357: 在此上下文中不允许表, 视图或序列引用" 的错误

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics