在hibernate中实现oracle的自动增长
根据hibernate的文档,有两种方式实现实体对象的主键自动增长。
第一种: 设置ID的增长策略是sequence,同时指定sequence的名字,最好每个表建一个sequence,此种做法就如同MS-SQL,MY-SQL中的自动增长一样,不需要创建触发器,具体的oracle数据库脚本及hibernate配置文件如下:
[1]oracle数据表的创建脚本:
- CREATE?TABLE?DEPARTMENT?(??
- ????ID?NUMBER(19 , 0 )?DEFAULT? '0' ?NOT?NULL,??
- ????NAME?VARCHAR2(255 )?NOT?NULL,??
-
????DESCRIPTION?CLOB??
-
);??
-
ALTER?TABLE?DEPARTMENT?ADD?CONSTRAINT?PRIMARY_0?PRIMARY?KEY(ID)?ENABLE;??
-
ALTER?TABLE?DEPARTMENT?ADD?CONSTRAINT?UK_DEPARTMENT_1?UNIQUE?(NAME);??
-
??
- CREATE?SEQUENCE?DEPARTMENT_ID_SEQ?MINVALUE?10000 ?MAXVALUE? 999999999999999999999999 ?INCREMENT?BY? 1 ?NOCYCLE;??
- CREATE?TABLE?DEPARTMENT?( ??
-
????ID?NUMBER(19,0)?DEFAULT?'0'?NOT?NULL, ??
-
????NAME?VARCHAR2(255)?NOT?NULL, ??
- ????DESCRIPTION?CLOB ??
- ); ??
- ALTER?TABLE?DEPARTMENT?ADD?CONSTRAINT?PRIMARY_0?PRIMARY?KEY(ID)?ENABLE; ??
- ALTER?TABLE?DEPARTMENT?ADD?CONSTRAINT?UK_DEPARTMENT_1?UNIQUE?(NAME); ??
- ??
-
CREATE?SEQUENCE?DEPARTMENT_ID_SEQ?MINVALUE?10000?MAXVALUE?999999999999999999999999?INCREMENT?BY?1?NOCYCLE;??
CREATE TABLE DEPARTMENT (
ID NUMBER(19,0) DEFAULT '0' NOT NULL,
NAME VARCHAR2(255) NOT NULL,
DESCRIPTION CLOB
);
ALTER TABLE DEPARTMENT ADD CONSTRAINT PRIMARY_0 PRIMARY KEY(ID) ENABLE;
ALTER TABLE DEPARTMENT ADD CONSTRAINT UK_DEPARTMENT_1 UNIQUE (NAME);
CREATE SEQUENCE DEPARTMENT_ID_SEQ MINVALUE 10000 MAXVALUE 999999999999999999999999 INCREMENT BY 1 NOCYCLE;
创建DEPARTMENT表,并为DEPARTMENT表创建一个单独的SEQUENCE,名字为SEQUENCE_ID_SEQ,并不需要创建触发器。
[2]hibernate映射文件的配置:
- <?xml?version= "1.0" ?>??
-
<!DOCTYPE?hibernate-mapping?PUBLIC??
- ??????"-//Hibernate/Hibernate?Mapping?DTD?3.0//EN" ??
- ??????????"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >??
- <hibernate-mapping?