hibernate 中用sequnce 生成主键值

来源:互联网 发布:网络诈骗有追回的吗 编辑:程序博客网 时间:2024/05/20 05:30
1、在oracle 首先创建sequence

      create sequence seq_payment
      minvalue 1
      start with 1
      increment by 1
      cache 20;

   2.在你的entity中的配置
   
  1. @Id  
  2. @GeneratedValue(strategy = GenerationType.SEQUENCE,generator="payablemoney_seq")   
  3. @SequenceGenerator(name="payablemoney_seq", sequenceName="seq_payment")  
     

       这样再插入数据的时候,Hibernate回自动生成如下语句:
       
       hibernate: select seq_id.nextval from dual

   hibernate:  insert into YXJK.T_YXJK_WHRYTXL (XM0000, ZW0000, LXDH00, SJHM00, DZYJ00,   
                    IP0000,     ID0000) values (?, ?, ?, ?, ?, ?, ?)

   自动生成下一个序列值,然后将对象插入表中。
   在使用的时候需要注意,Hibernate对于sequence的主键的要求是一定要是shor,long,或者integer

 

想自己去拿的话可以采用下面这种方法

 

List results =entityManager.createNativeQuery("select BCF_SEQ1.NEXTVAL from DUAL").getResultList();
        int id_seq = ((BigDecimal) results.get(0)).intValue();