Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate entities auto-increment id's across tables rather than per table

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.

like image 844
000000000000000000000 Avatar asked Jan 19 '17 18:01

000000000000000000000


People also ask

Is it mandatory to make primary column of a table as auto increment?

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.

Do primary keys need to auto increment?

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.

What is GenerationType Auto?

The GenerationType. AUTO is the default generation type and lets the persistence provider choose the generation strategy.

How can we auto generate primary key in hibernate?

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.


1 Answers

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)
like image 124
fingerprints Avatar answered Oct 06 '22 23:10

fingerprints