OK, so finally I came up with this (basically a combination from diverse suggestions made by others at different points in time)
package org.hibernate.id;
import java.io.Serializable;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.type.Type;
public class UseExistingOrGenerateTabelNameSequenceIdGenerator extends org.hibernate.id.enhanced.SequenceStyleGenerator {
/**
* {@inheritDoc} If the instance to insert does contain an ID
* we use that id instead of an auto generated one.
*/
@Override
public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
Serializable id = session.getEntityPersister(null, object).getClassMetadata().getIdentifier(object, session);
return id != null ? id : super.generate(session, object);
}
/**
* {@inheritDoc} If the parameters do not contain a
* {@link SequenceStyleGenerator#SEQUENCE_PARAM} name, we assign one based on the
* table name.
*/
@Override
public void configure(final Type type, final Properties params, final Dialect dialect) {
if (params.getProperty(SEQUENCE_PARAM) == null || params.getProperty(SEQUENCE_PARAM).length() == 0) {
String tableName = params.getProperty(PersistentIdentifierGenerator.TABLE);
if (tableName != null) {
params.setProperty(SEQUENCE_PARAM, "seq_" + tableName);
}
}
super.configure(type, params, dialect);
}
}
To use it specifically on a domain class, you would include something like
static mapping = {
id generator:'org.hibernate.id.UseExistingOrGenerateTabelNameSequenceIdGenerator', params:[optimizer:'pooled', increment_size:10]
}
into your domain class definition, which also allows to specify an id pool and its size.
Seems to run great so far :)