Skip to content

Instantly share code, notes, and snippets.

@ehabqadah
Last active July 18, 2020 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ehabqadah/a24bff99b19a6fc3f3bec81010623911 to your computer and use it in GitHub Desktop.
Save ehabqadah/a24bff99b19a6fc3f3bec81010623911 to your computer and use it in GitHub Desktop.
/**
* A custom Id generator based on combination of long time hex string and UUID
*
* @author Ehab Qadah
*/
public class BaseIdentifierGenerator extends UUIDGenerator {
private static final int NUMBER_OF_CHARS_IN_ID_PART = -5;
@Override
public Serializable generate(SharedSessionContractImplementor session, Object obj) throws HibernateException {
// Generate a custom ID for the new entity
final String uuid = super.generate(session, obj).toString();
final long longTimeRandom = System.nanoTime() + System.currentTimeMillis()
+ new Random().nextLong() + Objects.hash(obj);
final String timeHex = Long.toHexString(longTimeRandom);
return StringUtils.substring(timeHex, NUMBER_OF_CHARS_IN_ID_PART)
+ StringUtils.substring(uuid, NUMBER_OF_CHARS_IN_ID_PART);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment