Video in progress
Why can't Hibernate batch INSERTs when `GenerationType.IDENTITY` is used?
With IDENTITY, the database assigns the id during the INSERT. Hibernate needs to know the id right away to make the entity managed, so on every persist() it sends the INSERT immediately and separately, and JDBC batching is effectively off.
📖 Answer
The persistence context stores entities by id. For an object to be managed after persist(), it needs an id. With IDENTITY (auto-increment) you can get the id only after the INSERT, so Hibernate can't defer the INSERT until flush.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
If you save 10,000 rows, that's 10,000 separate round trips, even if hibernate.jdbc.batch_size is set.
With SEQUENCE it's different: Hibernate fetches ids from the sequence ahead of time (up to 50 in one call with the pooled optimizer) and sends the INSERTs as a single batch at flush time.
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_seq")
@SequenceGenerator(name = "order_seq", sequenceName = "order_seq", allocationSize = 50)
private Long id;
On PostgreSQL or Oracle, if you do a lot of bulk writing, choose SEQUENCE. MySQL has no sequences (MariaDB does), so there you often have to live with IDENTITY or do the bulk writes through JDBC.
Sign up to mark studied questions and save your progress.