springdatabasespring-booth2

The generation of @Id is random on the H2 database


I'm trying to use the H2 database, and using the Spring @Id and GenerationType.IDENTITY annotation. The persistence of the data is in a file inside the project's DATA folder, so, when I restart the database and try to put a new element, the id goes from ID:3 to ID:33.

enter image description here

What might be going on? I'm new to database and Spring.

This is how a generating the id.

{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

}

Solution

  • If you are a beginner, could it just be a simple effect of inserting and deleting multiple times? That is, the number of a record that has been deleted is not reused. So if the last ID is 9, the next one will be 10, but if you delete ID 10, the next one will be 11 and not 10 again, and so on.

    And also, gaps in ID sequences can occur due to rolled-back transactions.

    or can be a problem from caching:

    H2 Sequence Caching:

    H2 uses a sequence cache for performance reasons. When an entity is persisted, H2 may allocate a block of IDs from the sequence, even if some of those IDs are not immediately used.

    If the application shuts down unexpectedly, the cached IDs might not be persisted, leading to gaps in the sequence upon restart.

    The default cache size for H2 sequences is 32. This means that up to 32 numbers might be skipped if the application closes without properly flushing the cache.