Skip to content

Instantly share code, notes, and snippets.

@shortthirdman
Created June 24, 2024 05:52
Show Gist options
  • Save shortthirdman/f5651835bfb546ad09a98e544280037e to your computer and use it in GitHub Desktop.
Save shortthirdman/f5651835bfb546ad09a98e544280037e to your computer and use it in GitHub Desktop.
Identifier Generator using Hibernate
package com.example.generator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.Configurable;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.Type;
import java.io.Serializable;
import java.util.Properties;
@Slf4j
public class IdGenerator implements IdentifierGenerator, Configurable {
private String columnName;
private String tableName;
@Override
public void configure(Type type, Properties parameters, ServiceRegistry serviceRegistry) {
columnName = parameters.getProperty("column-name");
tableName = parameters.getProperty("table-name");
}
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) {
String query = String.format("select max(%s) from %s", columnName, tableName);
log.info("Querying {} from the last maximum number", tableName);
try {
int maxId = 1;
var lastId = session.createNativeQuery(query, Integer.class).getSingleResult();
if (lastId != null) {
maxId = lastId + 1;
}
log.info("Maximum number for column {} --> {}", columnName, maxId);
return maxId;
} catch (HibernateException he) {
log.error("Error occurred while generating next ID for [{}, {}]:\n{}", columnName, tableName, ExceptionUtils.getFullStackTrace(he));
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment