Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom Hibernate UUID Generator
// Before
@Id
@Column(name = "entity_id")
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid2")
private String entityId;
// After
@Id
@Column(name = "entity_id")
@GeneratedValue(generator = "inquisitive-uuid")
@GenericGenerator(name = "inquisitive-uuid", strategy = "com.myapp.persistence.generators.InquisitiveUUIDGenerator")
private String entityId;
package com.myapp.persistence.generators;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.UUIDGenerator;
import org.hibernate.type.Type;
import java.io.Serializable;
import java.util.Properties;
/**
* Based on http://stackoverflow.com/a/5392349/566434
*/
public class InquisitiveUUIDGenerator extends UUIDGenerator {
private String entityName;
@Override
public void configure(Type type, Properties params, Dialect dialect) {
entityName = params.getProperty(ENTITY_NAME);
super.configure(type, params, dialect);
}
@Override
public Serializable generate(SessionImplementor session, Object object) {
Serializable id = session
.getEntityPersister(entityName, object)
.getIdentifier(object, session);
if (id == null) {
return super.generate(session, object);
} else {
return id;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.