Last active
April 11, 2020 19:05
-
-
Save azell/5655888 to your computer and use it in GitHub Desktop.
Attempting to integrate Spring Transaction with jOOQ 3.7.0
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
public class SpringExceptionTranslationExecuteListener | |
extends DefaultExecuteListener { | |
/** {@inheritDoc} */ | |
@Override | |
public void exception(ExecuteContext ctx) { | |
SQLException e = ctx.sqlException(); | |
if (e != null) { | |
String name = ctx.configuration().dialect().thirdParty().springDbName(); | |
/* Prefer product name, if available. */ | |
SQLExceptionTranslator translator = (name != null) | |
? new SQLErrorCodeSQLExceptionTranslator(name) | |
: new SQLStateSQLExceptionTranslator(); | |
ctx.exception(translator.translate("jOOQ", ctx.sql(), e)); | |
} | |
} | |
} | |
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); | |
} | |
} |
Visitors of this gist:
Please do also consider the jOOQ manual's official tutorial on how to integrate jOOQ with Spring:
http://www.jooq.org/doc/latest/manual/getting-started/tutorials/jooq-with-spring/
Is there any particular reason for your recommendation of using that method over this one?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Visitors of this gist:
Please do also consider the jOOQ manual's official tutorial on how to integrate jOOQ with Spring:
http://www.jooq.org/doc/latest/manual/getting-started/tutorials/jooq-with-spring/