Skip to content

Instantly share code, notes, and snippets.

@pmcdaniel
Last active December 20, 2015 14:38
Show Gist options
  • Save pmcdaniel/6147616 to your computer and use it in GitHub Desktop.
Save pmcdaniel/6147616 to your computer and use it in GitHub Desktop.
Drop in replacement for Hibernate (3.6)'s GUIDGenerator for ID columns that uses Java's UUID to generate the GUID if the database doesn't support the GUID generator. Useful for testing with in-memory databases that don't support GUID
package org.patrickmcdaniel.util
import groovy.util.logging.Log4j
import org.hibernate.HibernateException
import org.hibernate.engine.SessionImplementor
import org.hibernate.exception.JDBCExceptionHelper
import org.hibernate.id.IdentifierGenerator
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.sql.SQLException
/**
* 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 {
@Override
Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
try {
final String sql = session.getFactory().getDialect().selectGUIDString
try {
PreparedStatement st = session.getBatcher().prepareSelectStatement(sql)
try {
ResultSet rs = st.executeQuery()
try {
rs.next()
return rs.getString(1)
}
finally {
rs.close()
}
}
finally {
session.getBatcher().closeStatement(st)
}
}
catch (SQLException sqle) {
throw JDBCExceptionHelper.convert(session.getFactory().getSQLExceptionConverter(), sqle, "could not retrieve GUID", sql)
}
}
catch (UnsupportedOperationException uoe) {
log.debug "Current database does not support GUID generator, generating our own"
return UUID.randomUUID().toString()
}
}
}
@burtbeckwith
Copy link

I reworked this a bit, taking advantage of the object being reused (and stateful) to remember that getSelectGUIDString() failed, and also using groovy.sql.Sql to simplify the JDBC code: https://gist.github.com/burtbeckwith/6148257

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment