0

I have the follwoing sequence defined in oracle:

CREATE SEQUENCE MySequence
MINVALUE 65536 
MAXVALUE 4294967296 
START WITH 65536
INCREMENT BY 1
CYCLE
NOCACHE
ORDER;

I wonder how can I access this via Hibernate (the next value each time i request) ? (via JDBC i have used getGEnerateKeys)

I need the id before I use it on another entity that needs to be persisted.

Thanks

Cris
  • 4,947
  • 6
  • 44
  • 73

3 Answers3

1

I think that as long as the sequence is your primary key - for example

@Id
@GeneratedValue(strategy = GenerationType.AUTO) 
private int id;

Then when you run:

 Integer id = (Integer)session.save(obj);  

It will return the id.

See the Javadoc: http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html#save(java.lang.Object)

Dan
  • 1,030
  • 5
  • 12
1

There's no JPA-standard way to do that, but you can certainly get access to the underlying JDBC connection, if you really need to. But note that, once the entity is persisted, the ID for the entity should be populated automatically.

jpkroehling
  • 13,881
  • 1
  • 37
  • 39
1

For Oracle you should use GenerationType.SEQUENCE

  @Id
    @GeneratedValue(generator="MySequence", strategy=GenerationType.SEQUENCE)
    @SequenceGenerator(allocationSize=1, name="MySequence", sequenceName="MySequence")

Edit: sequencename updated

Edit: refer to your comment: Your requirement sounds like composit/embedded id (using multiple columns as primary key) using sequence. but unfortunately both solution doesnt support sequence generator. So far I can say;

*You can create a native query via hibernate and append to index number using 'select mySequence.nextval from dual.

*Or you can create an oracle view for that with the new column which is showing sequence + index via subquery.

*This one very experimental and I didnt try but you can use @formula annotation. Example here.

Community
  • 1
  • 1
HRgiger
  • 2,750
  • 26
  • 37
  • I do not need the sequence to use it as an Id. I need the sequence because some entity which has it's own Id needs to have this let's call it 'index' which is a number between x and y. So the code will be something : give me next value from sequence and set to the enity then save. (so the entity will have it's own id) – Cris Aug 21 '12 at 11:21
  • Maybe i am not very clear...This value from sequence i define on oracle , is not an Id of the enity , it is just a value i want to set it to the entity (the entity has it's own id maybe via another sequence) – Cris Aug 21 '12 at 12:30