0

I am developing a spring 3 MVC application. I am using hibernate as the ORM. While defining the model, i have an ID field. I want to auto generate it in such a way that its value is the current number of rows in the table + 1. How can it be done?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Kaushik Balasubramanain
  • 1,248
  • 6
  • 28
  • 42

1 Answers1

2

AUTOINCREMENT column or a sequence will do the trick. In Hibernate simply annotate id with @GeneratedValue:

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

Hibernate will automatically set the id to next available value.

See also

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • hi. the issues here is that certain elements may be deleted at some time. in this case, when i add a new element, the id is not in sequence but is equal to the total number of elements added at one point to the table. – Kaushik Balasubramanain Apr 13 '12 at 21:36
  • 1
    @KaushikBalasubramanain: I know. But imagine: when you add three records they will have 1, 2 and 3 ids, right? Then when you delete first or second and add another one, according to your algorithm it should have id 3 (2 records in the database exist at a time) - but record with such id already exists! – Tomasz Nurkiewicz Apr 13 '12 at 21:42