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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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)
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)
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)

1 Comment

Thanks ...Please see my above comment.
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.

1 Comment

Thanks ...Please see my above comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.