试过sequence,自增序列+触发器,可是不能把id的值返回,或许是我不会。
考虑性能和返回主键到页面中去,到底应该用什么主键生成???

解决方案 »

  1.   

    oracle:sequence
    mysql:auto_increment
      

  2.   


    UUID.randomUUID().toString();
      

  3.   

    oracle  sequence能将新增的ID返回出来吗?
    我怎么老是取不到。
      

  4.   

    解决鸟,完美。
    答案是:native网上查了一下资料,native算是策略中的策略,在于数据库移植有优势,而sequence,如果有一天,要把数据库移到mysql,就惨了。
    native可以选择主键生成策略,如果是mysql,他会使用auto_increment方式生成主键;如果是oracle就是sequence。只是在使用oracle的时候,另外需要增加sequence。
    完整的代码如下:<hibernate-mapping>
      <class table="t_user" name="com.gwtjs.model.User">
        <id access="field" name="id" length="32">
          <generator class="native"/>
        </id>
        <property name="userName" length="32" access="field" unique="true" not-null="true" type="string"/>
        <property name="userPwd" length="32" access="field" not-null="true" type="string"/>
      </class>
    </hibernate-mapping>
    数据库脚本:-- Create table
    create table T_USER
    (
      id       VARCHAR2(32) not null,
      username VARCHAR2(32) not null,
      userpwd  VARCHAR2(32) not null
    )
    tablespace FOUNDDB
      pctfree 10
      initrans 1
      maxtrans 255
      storage
      (
        initial 64K
        minextents 1
        maxextents unlimited
      );
    -- Create/Recreate primary, unique and foreign key constraints 
    alter table T_USER
      add primary key (ID)
      using index 
      tablespace FOUNDDB
      pctfree 10
      initrans 2
      maxtrans 255
      storage
      (
        initial 64K
        minextents 1
        maxextents unlimited
      );
    alter table T_USER
      add unique (USERNAME)
      using index 
      tablespace FOUNDDB
      pctfree 10
      initrans 2
      maxtrans 255
      storage
      (
        initial 64K
        minextents 1
        maxextents unlimited
      );-- 公用的主键标识seq
    CREATE SEQUENCE HIBERNATE_SEQUENCE MINVALUE 1 MAXVALUE 999999999999999999999999 INCREMENT BY 1 NOCYCLE;-- create user table sequence
    create sequence t_user_seq
    minvalue 1
    maxvalue 9999999999
    start with 1
    increment by 1
    nocache;
    -- 插入用户的触发器
    create or replace trigger tri_insert_user
    before insert on t_user
    for each row 
      begin 
        select t_user_seq.nextval into :new.id from dual;
      end;