Created
June 27, 2014 16:03
-
-
Save 0x6e6562/95844ed3ef981a0c227b to your computer and use it in GitHub Desktop.
Just some glue to execute a bunch of statements in one TX using the JOOQ API
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 <T> T execute(Function<DSLContext,T> fun) { | |
T result = null; | |
Connection connection = null; | |
DatabaseException userException = null; | |
try { | |
connection = dataSource.getConnection(); | |
connection.setAutoCommit(false); | |
DSLContext ctx = DSL.using(connection, dialect, settings); | |
try { | |
result = fun.apply(ctx); | |
} catch (Exception e) { | |
String msg; | |
if (e instanceof DataAccessException) { | |
msg = e.getCause().getMessage(); | |
if (e.getCause() instanceof SQLIntegrityConstraintViolationException) { | |
SQLIntegrityConstraintViolationException ve = (SQLIntegrityConstraintViolationException) e.getCause(); | |
if (ve.getErrorCode() == 1062) { // http://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html#error_er_dup_key | |
String template = "Duplicate entry '(.*)' for key '(.*)'"; | |
Pattern pattern = Pattern.compile(template); | |
Matcher matcher = pattern.matcher(ve.getMessage()); | |
if (matcher.matches()) { | |
String key = matcher.group(1); | |
String value = matcher.group(2); | |
userException = new DuplicateKeyException(msg, key, value); | |
} | |
} | |
} | |
} else { | |
msg = e.getMessage(); | |
} | |
log.error(msg); | |
if (userException == null) { | |
userException = new DatabaseException(msg); | |
} | |
if (!connection.isClosed()) { | |
connection.rollback(); | |
} | |
} | |
if (null == userException) { | |
connection.commit(); | |
} | |
} catch (SQLException e) { | |
throw new DatabaseException(e.getMessage()); | |
} finally { | |
try { | |
// Release the connection back to the pool | |
if (null != connection && !connection.isClosed()) { | |
connection.close(); | |
} | |
} catch (SQLException e) { | |
throw new DatabaseException(e.getMessage()); | |
} | |
} | |
if (userException != null) { | |
throw userException; | |
} else { | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment