Forked from pmcdaniel/UuidIdentifierGenerator.groovy
Last active
December 20, 2015 14:39
-
-
Save burtbeckwith/6148257 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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