Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting sequence in hibernate

 
avihai marchiano
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
avihai marchiano
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that not.

Surrogate key , dosnt need to be part of the bussiness.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic