I'm initializing Hibernate without any XML by something like
org.hibernate.SessionFactory sessionFactory =
new org.hibernate.cfg.Configuration().
.setProperty(...)
.setProperty(...)
...
.buildSessionFactory();
My classes use an ID like
@Id @Generated(GenerationTime.INSERT) @GeneratedValue private Integer id;
The generator used is SequenceStyleGenerator
, which seems to be the replacement for the deprecated SequenceGenerator
and SequenceHiLoGenerator
and whatever. It uses
public static final int DEFAULT_INCREMENT_SIZE = 1;
and seems to allow configuration via
public static final String INCREMENT_PARAM = "increment_size";
but that's all I could find out. I guess I have to set some property "xxx.yyy.increment_size" or pass it in another way to Hibernate, but I can't see how.
I'm aware of @SequenceGenerator
, but it seems to be completely ignored
@Generated vs @GeneratedValue
You don't need to use
@Generated
along with@GeneratedValue
. The@Generated
annotation is for non-id entity attributes that are generated by the database during INSERT or UPDATE. For more details about the@Generated
annotation, check out this article.On the other hand, the
@GeneratedValue
is only for the entity identifier attributes, and it's what you need to use when the entity identifier is generated automatically upon persisting an entity.Sequence generator
The sequence generator requires an extra database roundtrip to call the sequence object when you persist the entity. For this reason, Hibernate offers the sequence-based optimizers to reduce the number of roundtrips needed to fetch entity identifier values.
Now, if you want to use
hilo
, the identifier mapping will look as follows:Apart from having to use the Hibernate-specific
@GenericGenerator
, the problem withhilo
is that the generated identifiers don't include the database sequence value, so an 3rd-party client using the database will not know how to generate the next identifier value unless they know thehilo
algorithm and theallocationSize
.For this reason, it's better to use
pooled
orpooled-lo
.Pooled optimizer
The
pooled
optimizer is very easy to set up. All you need to do is set theallocationSize
of the JPA@SequenceGenerator
annotation, and Hibernate is going to switch to using thepooled
optimizer:Pooled-lo optimizer
To use the pooled-lo optimizer, just add the following configuration property:
Now, the entity identifier mapping is identical to the one I showed you before for the
pooled
optimizer.To understand how the pooled-lo works, check out this diagram:
I guess you are looking for how to set
increment_size
property for yourSequenceSytleGenerator
.Sample snippet below setting
increment_size
using@GenericGenerator
annotation withhilo
optimizer andSEQUENCE
strategy.There's no way you can globally set the
DEFAULT_INCREMENT_SIZE
with a Hibernate configuration property. You need to use the@Id
configuration properties instead.