11

Currently I have three tables: Company, Group, Person.

The three tables are connected by Company is one-to-many with Group and Group is one-to-many with Person.

In all three classes (Company.java, Group.java, Person.java), I coded the auto-increment unique id this way:

@Id
@Column(name = "id")
@GeneratedValue
private int id;

Then I instantiated all three classes in this order: Company, Group, Person.

After saving those objects to my database, I noticed that there is something wrong with the id's in the tables.

Apparently, rather than increasing the Company's id in the order 1, 2, 3, 4, so on; it is increasing in 1, 4, 7, 10...

In this same logic, Group's id goes 2, 5, 8, 11...

What should I do to prevent the @GeneratedValue counter being shared among the three different tables? Is there an additional or different tag I should use?

Thanks.

000000000000000000000
  • 780
  • 4
  • 15
  • 47

1 Answers1

18

That is probably because hibernate generate one table for the sequence of ids. Which DB are you working with? MySQL? or another database that do not use sequences?. You can try using:

 @GeneratedValue(strategy = GenerationType.IDENTITY)
carpinchosaurio
  • 1,175
  • 21
  • 44
fingerprints
  • 2,751
  • 1
  • 25
  • 45
  • 1
    Thanks! This worked in MySql for me and later in posgresql as well. – 000000000000000000000 Jan 19 '17 at 19:41
  • But if you have to migrate your db to oracle, then it won't work, because oracle doesn't support identity. What do you suggest in this case would be a good option> – Khatri Jul 03 '18 at 12:40
  • I got this error after changing the generation type from AUTO to IDENTITY: Field 'id' doesn't have a default value. – Bu Saeed Apr 07 '21 at 18:56