Hibernate + oracle序列+触发器 [英] Hibernate + oracle sequence + trigger
问题描述
我有一个索引自动填充的表,其中有一个使用序列(Oracle数据库)的触发器
CREATE TABLE A
(
IDS NUMBER(10)NOT NULL
)
创建或替换触发器A_TRG
插入前
ON A参考新的旧OLD AS旧
每行
BEGIN
:new.IDS:= A_SEQ.nextval;
END A_TRG;
/
我有一个匹配的Java类:
类A {
@Id
@SequenceGenerator(name =aSequence,sequenceName =A_SEQ,allocationSize = 1)
@GeneratedValue(generator =aSequence,strategy = GenerationType.SEQUENCE)
@Column(name =IDS)
Long id;
...
}
当我尝试坚持一个像这样的实例:
$ b $ pre $ EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
A a = new A();
Long id = getHibernateTemplate()。save(a);
transaction.commit();
我遇到这个问题: save调用返回的代码中的ID = X
有没有办法设置Hibernate来让数据库触发器创建ID?
谢谢 解决方案
使用Oracle触发器从序列中生成id的HIbernate问题
我必须调整我的触发器才能在没有ID的情况下运行:
<$ p $创建或替换触发器A_TRG
插入前
参考新的新旧OLD旧
每行
当(New.IDS为空时) - (1)
BEGIN
:new.IDS:= A_SEQ.nextval;
END A_TRG; (1)此行允许Hibernate手动调用A_SEQ.nextVal来设置ID,然后绕过触发器,否则Hibernate将无用地获得nextval,因为触发器会再次重置ID调用nextval。
I have a table with an index auto filled by a trigger that use a sequence (Oracle database)
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;
/
I have a matching Java class:
Class A {
@Id
@SequenceGenerator(name = "aSequence", sequenceName = "A_SEQ", allocationSize = 1)
@GeneratedValue(generator = "aSequence", strategy = GenerationType.SEQUENCE)
@Column(name = "IDS")
Long id;
...
}
When I try to persist an instance of A like this:
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
A a = new A();
Long id = getHibernateTemplate().save(a);
transaction.commit();
I get this problem:
ID in code returned by the save call = "X"
ID in database = "X+1"
Is there a way to setup Hibernate to let the database trigger create the ID ?
Thanks
Reponse found at HIbernate issue with Oracle Trigger for generating id from a sequence
I need to adapt my trigger to run only if no ID is given:
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) this line allow Hibernate to manually call A_SEQ.nextVal to set the ID and then bypass the trigger else Hibernate will get the nextval for uselessly because the trigger will always reset the ID calling nextval again
这篇关于Hibernate + oracle序列+触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!