Video in progress

Junior 🌱 Spring

How do the IDENTITY and SEQUENCE strategies in @GeneratedValue differ?

With IDENTITY the database assigns the id at INSERT time, so Hibernate has to INSERT every record immediately. With SEQUENCE the id is fetched from the sequence ahead of time, and batch inserts can work.

📖 Answer

@Entity
class Payment {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "payment_seq")
    @SequenceGenerator(name = "payment_seq", sequenceName = "payment_seq", allocationSize = 50)
    private Long id;
}

IDENTITY (MySQL AUTO_INCREMENT, PostgreSQL identity/serial):

  • the id is known only once the row is in the database;
  • so Hibernate sends the INSERT as soon as persist() is called;
  • JDBC batch insert doesn't work: 10,000 records means 10,000 separate queries.

SEQUENCE (PostgreSQL, Oracle):

  • Hibernate gets ids from the sequence and can delay the INSERT until flush;
  • with allocationSize = 50, the database is hit once per 50 ids;
  • together with hibernate.jdbc.batch_size it's much faster.

The trap: allocationSize and the sequence's INCREMENT BY in the database must match. If they don't, ids collide or big gaps appear.

If you leave GenerationType.AUTO, Hibernate 6 often picks SEQUENCE, which many people don't know.