-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 
Author Message
 Post subject: Hibernate + oracle sequence + trigger
PostPosted: Tue Nov 20, 2012 5:59 am 
Newbie

Joined: Tue Nov 20, 2012 5:45 am
Posts: 2
Hello,

I have a table with an index auto filled by a trigger that use a sequence (Oracle database):

Code:
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:

Code:
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:

Code:
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


Top
 Profile  
 
 Post subject: Re: Hibernate + oracle sequence + trigger
PostPosted: Tue Nov 20, 2012 6:31 am 
Newbie

Joined: Tue Nov 20, 2012 5:45 am
Posts: 2
I just found a workaround at http://stackoverflow.com/questions/8002119/hibernate-issue-with-oracle-trigger-for-generating-id-from-a-sequence

Code:
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


Top
 Profile  
 
 Post subject: Re: Hibernate + oracle sequence + trigger
PostPosted: Wed Nov 21, 2012 6:57 am 
Newbie

Joined: Wed Nov 21, 2012 6:55 am
Posts: 1
this might help: http://codermanual.blogspot.com/2012/11/hibernate-custom-sequence-for-oracle.html


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.