In JPA I want to autogenerate an integer primary key where the generation should start from, say, 1000. I’m new to JPA and I have used IDENTITY type earlier to avoid those extra id tables that JPA otherwise generates. I’ve tried using SEQUENCE but it generates a seperate id table as well.
Earlier code:
@Id
@Column(length = 4)
@GeneratedValue (strategy = GenerationType.IDENTITY)
private Integer reservationId;
For what I can see, you can’t get IDENTITY to increment from a specified starting point.
Is there any way I can use JPA to increment from a starting point and not get extra id tables?
2
Answers
You can try to use:
In this example name is the name of the sequence generator,
sequenceName is the name of the database sequence to use,
initialValue is the initial value of the sequence and
allocationSize is the increment size of the sequence.
Note: The SEQUENCE strategy requires a database sequence to be created, so you’ll need to ensure that your database supports sequences and that the sequence is created before running your (JPA) application.
I’m not an expert in MySQL, but searching the web it seems that MySQL doesn’t support sequences – at least, stricto sensu. So either you use
GenerationType.IDENTITY
orGenerationType.TABLE
.In order to prove the concept, let’s code a little. In the following examples, I will show the entity class, its metadata, and the SQL the persistence provider generated based on them.
GenerationType.IDENTITY
The entity class:
The generated SQL:
If you need to start the
AUTO_INCREMENT
column from a specific value, as per the documentation, a possible solution is to insert a row with that value and then delete it.GenerationType.SEQUENCE
The entity class:
The generated SQL:
Again, this is because MySQL does not support sequences. If the database used were one that supports sequences, a sequence creation would be seen above.
GenerationType.TABLE
The entity class:
The generated SQL:
It looks like the difference between
@SequenceGenerator
and@TableGenerator
in MySQL is that@TableGenerator
creates only one table with multiple rows to manage all the ids that reference it (the expected behavior, by the way), while@SequenceGenerator
creates a table for each annotation.GenerationType.UUID
I decided – why not?, to see what happens when using the UUID generation type.
The entity class:
The generated SQL:
Only the table is created. This suggests that the id generation, in this case, is managed by the persistence provider – which is actually what the specification says.
IMPORTANT
persistence.xml
file. If you are using Hibernate, you should add the following line:To enable the SQL script schema generation, you have to set in
persistence.xml
file the propertiesjakarta.persistence.schema-generation.scripts.action
andjakarta.persistence.schema-generation.scripts.create-target
.Note that the
next_val
columns are defined asbigint
. So, if you are going to use a sequence or table generator, I suggest you to set the entity id field as a Long.