Last active
December 20, 2015 14:38
-
-
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
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.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() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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