Hibernate + oracle序列+触发器

时间:2012-11-16 14:04:34

标签: oracle hibernate jpa persistence sequence

我有一个表,其索引由使用序列(Oracle数据库)的触发器自动填充

CREATE TABLE A
(
  IDS                           NUMBER(10)      NOT NULL
)


CREATE OR REPLACE TRIGGER A_TRG
BEFORE INSERT
ON A REFERENCING NEW AS New OLD AS Old
FOR EACH ROW
BEGIN
  :new.IDS := A_SEQ.nextval;
END A_TRG;
/

我有一个匹配的Java类:

Class A {
   @Id
   @SequenceGenerator(name = "aSequence", sequenceName = "A_SEQ", allocationSize = 1)
   @GeneratedValue(generator = "aSequence", strategy = GenerationType.SEQUENCE)
   @Column(name = "IDS")
   Long id;

   ...
}

当我尝试像这样坚持A的实例时:

EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
A a = new A();
Long id = getHibernateTemplate().save(a);
transaction.commit();

我遇到了这个问题:

  • 保存电话返回的代码中的ID = “X”

  • 数据库中的ID = “X + 1”

有没有办法设置Hibernate让数据库触发器创建ID?

由于

2 个答案:

答案 0 :(得分:11)

HIbernate issue with Oracle Trigger for generating id from a sequence

找到了回复

我需要调整我的触发器才能在没有给出ID的情况下运行:

CREATE OR REPLACE TRIGGER A_TRG
BEFORE INSERT
ON A REFERENCING NEW AS New OLD AS Old
FOR EACH ROW
WHEN (New.IDS is null) -- (1)
BEGIN
  :new.IDS := A_SEQ.nextval;
END A_TRG;
/

(1)这一行允许Hibernate手动调用A_SEQ.nextVal来设置ID,然后绕过触发器,否则Hibernate将无用地获取nextval,因为触发器将始终重置ID再次调用nextval

答案 1 :(得分:1)

在您的班级B中,您拥有的@GeneratedValue(generator = "preferenceSequence")未在您拥有的示例中定义,它应为@GeneratedValue(generator = "bSequence")

默认情况下,hibernate分配大小为50 B:IDS = 50似乎表明映射正在选择错误的序列。