Home > Blockchain >  Can be GenerationType.SEQUENCE optimized to not to perform query to sequence on every ID update?
Can be GenerationType.SEQUENCE optimized to not to perform query to sequence on every ID update?

Time:04-19

When I use

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

Does it mean, on every entity creation ORM framework makes a query to DB to update sequence table? Can it be optimized, e.g. by chunks?

CodePudding user response:

@GeneratedValue further exposes an option to define a generator :

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

Enabling this , Hibernate will allocate a batch of 50 ids per session.This batch will be then prefetch for a range of 50 which can provide better performance.

There are still some additional things to be considered , such as , if a session is closed/killed prematurely we will lose the allocated sequence ids.

The following deep-dive talks more about the caveats/soltions : https://www.jpa-buddy.com/blog/the-ultimate-guide-on-db-generated/

  • Related