Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA, GeneratedValue autoincrement with 50

Tags:

java

jpa

entity

I'm using JPA and when I insert data into the database my ID is autoincremented with 50. I'm using persistence.GeneratedValue to autoincrement it:

This is how my model/entity class looks like (Entity to be inserted):

..imports
@Entity
public class Example extends Identifiable  {
   ..
}

Identifiable :

..imports
@MappedSuperclass
public abstract class Identifiable {
    @Id @GeneratedValue protected long id;
    ..
}

Database:

#    ID    NAME    ...
1    701   a
2    751   b
3    801   c

Anyone have an Idea what the problem is?

like image 517
user3231419 Avatar asked Oct 26 '25 12:10

user3231419


1 Answers

Default value for GeneratedValue.strategy is GenerationType.AUTO. What this means is spelled out nicely in JPA 2 specification:

The AUTO value indicates that the persistence provider should pick an appropriate strategy for the particular database. The AUTO generation strategy may expect a database resource to exist, or it may attempt to create one. A vendor may provide documentation on how to create such resources in the event that it does not support schema generation or cannot create the schema resource at runtime.

For both TableGenerator and SequenceGenerator default value of allocationSize is 50. This means that chunk of 50 values is reserved. In shutdown there reserved values will be gone. If application is shutdown after only one is used, values from 2 to 50 are gone and next time 51 to 100 will be reserved. Strategy other than auto should be used if more control over identifier generation is needed. That can be done for example as follows:

@TableGenerator(
  name = "yourTableGenerator"
  allocationSize = 1,
  initialValue = 1)
@Id 
@GeneratedValue(
  strategy=GenerationType.TABLE, 
  generator="yourTableGenerator")

or:

@SequenceGenerator(name="yourSequenceGenerator", allocationSize=1)
@Id 
@GeneratedValue(strategy=GenerationType.SEQUENCE, 
                generator="yourSequenceGenerator")
like image 196
Mikko Maunu Avatar answered Oct 28 '25 01:10

Mikko Maunu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!