Hibernate handles id assigning instead of database

I have an auto-increment PK in a table and I want hibernate to handle id assigning instead of database. As my understanding the @GeneratedValue(strategy = GenerationType.IDENTITY) lets the database generate a new value with each insertion operation. So do we have any different solution to handle it?

1 answer

  • answered 2022-05-07 07:08 ahsan

    JPA offers 4 different ways to generate primary key values

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

    Example:

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    

    IDENTITY: It relies on an auto-incremented database column and lets the database generate a new value with each insert operation.

    Example:

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

    SEQUENCE: For this type Hibernate requests the primary key value from a database sequence.

    Example:

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "book_generator")
    @SequenceGenerator(name="book_generator", sequenceName = "book_seq", allocationSize=50)
    private Long id;
    

    TABLE: It simulates a sequence by storing and updating its current value in a database table which requires the use of pessimistic locks which put all transactions into a sequential order.

    Example:

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "book_generator")
    @TableGenerator(name="book_generator", table="id_generator", schema="bookstore")
    private Long id;
    

    I prefer to use the GenerationType.SEQUENCE because it is very efficient and allows Hibernate to decide when to perform the insert statement. This provides the required flexibility to use other performance optimization techniques like JDBC batching.

    For more details check this link.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum