Is Hibernate batching with IDENTITY generation possible?

Viewed 428

I just read this article which says how to do batching with hibernate but at the end it says it was done with SEQUENCE generation. I am wondering if it is possible with IDENTITY generation though. From reading around it sounds like IDENTITY generation is done at execute of INSERT which means that it could be too late?

ie. If I

mgr.persist(child)
mgr.persist(parent)

in a loop, BUT I want batching, the child would not have the id until mgr.flush() since the insert is delayed until flush time. Looking at IDENTITY generation:

The only drawback is that we can’t know the newly assigned value prior to executing the INSERT statement.

So this is implying that I would have to then

mgr.persist(child), mgr.persist(child), mgr.persist(child)

then mgr.flush() for id population

then

mgr.persist(parent, mgr.persist(parent), mgr.persist(parent)

We are in mysql and 'could' switch so that we are in postgres which has better support for sequence generation AND pooling so it grabs 50 ids at a time.

My main question is if anyone has done batching with hibernate AND with IDENTITY generation along with child/parent relationships to slam data in for a batch? And if so, what patterns work? Does my above pattern work? or am I wrong and I could do

mgr.persist(child), mgr.persit(parent), mgr.persist(child), mgr.persist(parent)

WHICH to be honest is simpler to keep as I can just loop over DTO's saving that data.

If I use UUID generation instead, I am assuming that would be much better with MysqL? Then I don't have to worry about code order?

1 Answers

Hibernate documentation says about this limitation:

It is important to realize that using IDENTITY columns imposes a runtime behavior where the entity row must be physically inserted prior to the identifier value being known.

This can mess up extended persistence contexts (long conversations). Because of the runtime imposition/inconsistency, Hibernate suggests other forms of identifier value generation be used (e.g. SEQUENCE).

There is yet another important runtime impact of choosing IDENTITY generation: Hibernate will not be able to batch INSERT statements for the entities using the IDENTITY generation.

The importance of this depends on the application-specific use cases. If the application is not usually creating many new instances of a given entity type using the IDENTITY generator, then this limitation will be less important since batching would not have been very helpful anyway.

Related