This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Object Relational Mapping and the fly likes Getting sequence in hibernate Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Databases » Object Relational Mapping
Bookmark "Getting sequence in hibernate" Watch "Getting sequence in hibernate" New topic
Author

Getting sequence in hibernate

avihai marchiano
Ranch Hand

Joined: Jan 10, 2007
Posts: 342
Hey,

One of my field (not the ID) need to have a unique value (int smaller than 10,000).
I decide to write sequence in the DB and get this field value from the sequence , can hibernate help me to do this in generic way?

Thank you
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

You can access sequences for purposes other than ids by mapping the sequence as a named sql query. Something like:


However, if you are using sequences your solution is no longer generic (since it doesn't work on databases that don't support sequences). You will also run out of numbers long before you hit your 10,000 limit because sequences don;t guarentee to increment by one.

All that aside, if you have a unique, unchanging property of an entity that is not null, why not make it part of your primary key?


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
avihai marchiano
Ranch Hand

Joined: Jan 10, 2007
Posts: 342
Thanks a lot for your answer.

1. i love to use in surrogate keys, so its not part of my primary key.
2. i need "generic" for MySql and Oracle.
3. i work with JPA , so should i add it as a NamedQuery?

Thank you
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336


1. i love to use in surrogate keys, so its not part of my primary key.

Fair enough, its good practice, in my opinion. Doesn't this particular field have all the characteristics of a surrogate key though?
avihai marchiano
Ranch Hand

Joined: Jan 10, 2007
Posts: 342
I think that not.

Surrogate key , dosnt need to be part of the bussiness.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Getting sequence in hibernate