2

I'd like to have a column for member numbers which are unique. What's the best way to do this with Hibernate/JPA?

What's the best way to generate a unique integer combination of, say, 10 digits, that can be used as a member number?

EDIT
@Generated(GenerationTime.INSERT)
@Column(insertable = false)
private int membernumber;
user3629892
  • 2,960
  • 9
  • 33
  • 64

1 Answers1

0

I researched the topic a bit and found that the JPA specification allow @GeneratedValue for non ID columns, but hibernate does not.

JPA or Hibernate to generate a (non primary key) column value, not starting from 1

You could use an insert trigger in your database or generate it by hand in your service before saving the entity. That link have a good discussion about that.

Hope it helps.

Community
  • 1
  • 1
  • Thanks for your reply! Which part of the question was not clear to you? Maybe I can clarify and you can optimize your answer if necessary. Basically, I have a table that stores members. That table has a primary key. However, I also want to have a unique member number for each member. is there a way of implementing a counter or something, that starts at 10000 and then just increments? – user3629892 Jul 10 '15 at 16:39
  • I Think I got it, I thought you wanted a unique random value for each registry. In that case you can use an @Generated in your column and change the database to auto-increment that value starting at 10000 (Sequence for Postgres, auto_increment for MySQL). Here's a good example: http://www.concretepage.com/hibernate/example-generated-hibernate – Henrique Fontana Jul 10 '15 at 17:13
  • Hello! I cannot get it to work. See my edit: I get the error that the column doesnt have a default value. – user3629892 Jul 18 '15 at 08:51
  • Sorry for the long time to answer. Did you defined that column as auto_increment in your database? – Henrique Fontana Jul 20 '15 at 13:02
  • Friend, I edited my answer. Only OpenJPA allow what I suggested you.Take a look at the answer, please. – Henrique Fontana Jul 20 '15 at 13:43