Reputation: 6236
The Hibernate documentation says:
Hibernate disables insert batching at the JDBC level transparently if you use an identity identifier generator.
But all my entities have this configuration:
@Id
@GeneratedValue(strategy = javax.persistence.GenerationType.IDENTITY)
private Integer id;
When I'm using this identity above So
IDENTITY
?Upvotes: 60
Views: 28959
Reputation: 153700
Hibernate tries to defer the Persistence Context flushing up until the last possible moment. This strategy has been traditionally known as transactional write-behind.
The write-behind is more related to Hibernate flushing rather than any logical or physical transaction. During a transaction, the flush may occur multiple times.
The flushed changes are visible only for the current database transaction. Until the current transaction is committed, no change is visible by other concurrent transactions.
The IDENTITY
generator allows an int
or bigint
column to be auto-incremented on demand. The increment process happens outside of the current running transaction, so a roll-back may end up discarding already assigned values (value gaps may happen).
The increment process is very efficient since it uses a database internal lightweight locking mechanism as opposed to the more heavyweight transactional course-grain locks.
The only drawback is that we can’t know the newly assigned value prior to executing the INSERT statement. This restriction is hindering the transactional write-behind flushing strategy adopted by Hibernate. For this reason, Hibernates disables the JDBC batch support for entities using the IDENTITY
generator.
The only solution would be to use a TABLE
identifier generator, backed by a pooled-lo
optimizer. This generator works with MySQL too, so it overcomes the lack of database SEQUENCE support.
However, the TABLE
generator performs worse than IDENTITY
, so in the end, this is not a viable alternative.
Therefore, using IDENTITY is still the best choice on MySQL, and if you need batching for insert, you can use JDBC for that.
Upvotes: 85