日期:2014-05-16  浏览次数:20533 次

在hibernate中实现oracle的自动增长

根据hibernate的文档,有两种方式实现实体对象的主键自动增长。
第一种: 设置ID的增长策略是sequence,同时指定sequence的名字,最好每个表建一个sequence,此种做法就如同MS-SQL,MY-SQL中的自动增长一样,不需要创建触发器,具体的oracle数据库脚本及hibernate配置文件如下:

[1]oracle数据表的创建脚本:

  1. CREATE?TABLE?DEPARTMENT?(??
  2. ????ID?NUMBER(19 , 0 )?DEFAULT? '0' ?NOT?NULL,??
  3. ????NAME?VARCHAR2(255 )?NOT?NULL,??
  4. ????DESCRIPTION?CLOB??
  5. );??
  6. ALTER?TABLE?DEPARTMENT?ADD?CONSTRAINT?PRIMARY_0?PRIMARY?KEY(ID)?ENABLE;??
  7. ALTER?TABLE?DEPARTMENT?ADD?CONSTRAINT?UK_DEPARTMENT_1?UNIQUE?(NAME);??
  8. ??
  9. CREATE?SEQUENCE?DEPARTMENT_ID_SEQ?MINVALUE?10000 ?MAXVALUE? 999999999999999999999999 ?INCREMENT?BY? 1 ?NOCYCLE;??
Java代码 复制代码
  1. CREATE?TABLE?DEPARTMENT?( ??
  2. ????ID?NUMBER(19,0)?DEFAULT?'0'?NOT?NULL, ??
  3. ????NAME?VARCHAR2(255)?NOT?NULL, ??
  4. ????DESCRIPTION?CLOB ??
  5. ); ??
  6. ALTER?TABLE?DEPARTMENT?ADD?CONSTRAINT?PRIMARY_0?PRIMARY?KEY(ID)?ENABLE; ??
  7. ALTER?TABLE?DEPARTMENT?ADD?CONSTRAINT?UK_DEPARTMENT_1?UNIQUE?(NAME); ??
  8. ??
  9. 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映射文件的配置:

  1. <?xml?version= "1.0" ?>??
  2. <!DOCTYPE?hibernate-mapping?PUBLIC??
  3. ??????"-//Hibernate/Hibernate?Mapping?DTD?3.0//EN" ??
  4. ??????????"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >??
  5. <hibernate-mapping?