Skip to content

Instantly share code, notes, and snippets.

@paulogaspar7
Forked from azell/Spring Txn and jOOQ 3.7.0
Created March 3, 2014 15:00
Show Gist options
  • Save paulogaspar7/9326785 to your computer and use it in GitHub Desktop.
Save paulogaspar7/9326785 to your computer and use it in GitHub Desktop.
public class SpringExceptionTranslationExecuteListener
extends DefaultExecuteListener {
/** {@inheritDoc} */
@Override
public void exception(ExecuteContext ctx) {
String name = productName(ctx.configuration().dialect());
/* Prefer product name, if available. */
SQLExceptionTranslator translator = (name != null)
? new SQLErrorCodeSQLExceptionTranslator(name)
: new SQLStateSQLExceptionTranslator();
ctx.exception(translator.translate("jOOQ", ctx.sql(), ctx.sqlException()));
}
protected String productName(SQLDialect dialect) {
String name = null;
if (dialect == SQLDialect.HSQLDB) {
name = "HSQL";
} else if (dialect == SQLDialect.POSTGRES) {
name = "PostgreSQL";
} else if (dialect == SQLDialect.MARIADB) {
name = SQLDialect.MYSQL.getName();
} else if (dialect != null) {
name = dialect.getName();
}
return name;
}
}
public class SpringTransactionConnectionProvider implements ConnectionProvider {
private final DataSource ds;
public SpringTransactionConnectionProvider(DataSource ds) {
this.ds = ds;
}
/** {@inheritDoc} */
@Override
public Connection acquire() {
try {
return DataSourceUtils.doGetConnection(ds);
} catch (SQLException e) {
throw new DataAccessException(
"Error getting connection from data source " + ds, e);
}
}
/** {@inheritDoc} */
@Override
public void release(Connection conn) {
try {
DataSourceUtils.doReleaseConnection(conn, ds);
} catch (SQLException e) {
throw new DataAccessException("Error closing connection " + conn, e);
}
}
}
public class JooqTransactionFactory {
private final Configuration config = new DefaultConfiguration();
public JooqTransactionFactory(DataSource ds, SQLDialect dialect) {
this(ds, dialect, new Settings().withRenderSchema(false));
}
public JooqTransactionFactory(DataSource ds, SQLDialect dialect,
Settings settings) {
config.set(new SpringTransactionConnectionProvider(ds)).set(dialect).set(
settings).set(
new DefaultExecuteListenerProvider(
new SpringExceptionTranslationExecuteListener()));
}
public DSLContext context() {
return DSL.using(config);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment