-
-
Save azell/efbccdcb670d3f03567b to your computer and use it in GitHub Desktop.
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