Hibernate + oracle sequence + trigger

I have a table with an index automatically populated by a trigger that uses 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 corresponding 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 save 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:

  • Identifier in the code returned by save = "X"

  • Database ID = "X + 1"

Is there a way to configure Hibernate so that the database trigger creates an identifier?

thanks

+6
source share
2 answers

Failure Found in HIbernate Problem Using Oracle Trigger to Generate Identifier from Sequence

I need to configure my trigger to run only if no ID is specified:

 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 allows Hibernate to manually call A_SEQ.nextVal to set the identifier, and then bypass the trigger yet. Hibernate will get nextval for uselessness, because the trigger will always be reset by calling the ID again

+11
source

In your class B, you have @GeneratedValue(generator = "preferenceSequence") , which is not listed in the example you have, it should be @GeneratedValue(generator = "bSequence")

By default, the sleep size in sleep mode is 50: B: IDS = 50, it seems that assumes the matching is choosing the wrong sequence.

+1
source

All Articles