Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save burtbeckwith/6148257 to your computer and use it in GitHub Desktop.
Save burtbeckwith/6148257 to your computer and use it in GitHub Desktop.
package org.patrickmcdaniel.util
import groovy.sql.Sql
import groovy.util.logging.Log4j
import java.sql.Connection
import org.hibernate.HibernateException
import org.hibernate.engine.SessionImplementor
import org.hibernate.id.IdentifierGenerator
import org.hibernate.jdbc.Work
/**
* Generates a string value to use for an id column using dialect specific SQL function, or if unsupported
* we will generate one using Java's UUID class
*
* All code is based on Hibernate 3.6
*/
@Log4j
class UuidIdentifierGenerator implements IdentifierGenerator {
private boolean supported = true
Serializable generate(SessionImplementor session, obj) throws HibernateException {
if (!supported) {
return UUID.randomUUID().toString()
}
try {
final String sql = session.factory.dialect.selectGUIDString
String guid
session.doWork new Work() {
void execute(Connection c) {
guid = new Sql(c).firstRow(sql)[0]
}
}
guid
}
catch (UnsupportedOperationException e) {
supported = false
log.debug "Current database does not support GUID generator, generating our own"
return UUID.randomUUID().toString()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment