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.
No. A primary key must be unique and that has to be 100% guaranteed, and NON NULL A primary key should be stable if ever possible and not change. So you don't have to, but it's a good choice since there is no other naturally unique data and you don't want to have enormous primary keys.
To have an auto-increment PK makes it easy to create a key that never needs to change, which in turn makes it easy to reference in other tables. If your data is such that you have natural columns that are unique and can never change you can use them just as well.
The GenerationType. AUTO is the default generation type and lets the persistence provider choose the generation strategy.
If we want to automatically generate the primary key value, we can add the @GeneratedValue annotation. This can use four generation types: AUTO, IDENTITY, SEQUENCE and TABLE. If we don't explicitly specify a value, the generation type defaults to AUTO.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With