Skip to content

Instantly share code, notes, and snippets.

@rattanchauhan
Last active December 9, 2018 12:15
Show Gist options
  • Save rattanchauhan/2c5660e0792a2334b1561a2b798a1565 to your computer and use it in GitHub Desktop.
Save rattanchauhan/2c5660e0792a2334b1561a2b798a1565 to your computer and use it in GitHub Desktop.
Simple Jdbc Template with connection provider in Java 8
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import app.example.exception.DataAccessException;
public class JdbcTemplate {
private Supplier<Connection> connectionProvider;
public JdbcTemplate(Supplier<Connection> connectionProvider) {
this.connectionProvider = connectionProvider;
}
private static final Log LOG = LogFactory.getLog(JdbcTemplate.class);
public <R> R query(final String sql, final Function<ResultSet, R> mapper) {
LOG.info("Executing SQL query [" + sql + "]");
try (Connection con = connectionProvider.get()) {
try (PreparedStatement st = con.prepareStatement(sql)) {
java.sql.ResultSet resultSet = st.executeQuery();
return mapper.apply(resultSet);
} catch (SQLException e) {
throw new DataAccessException("SQLException whle reading database {} ", e);
}
} catch (SQLException e) {
throw new DataAccessException("SQLException whle connecting to database {} ", e);
}
}
public void query(final String sql, final Consumer<ResultSet> consumer) {
LOG.info("Executing SQL query [" + sql + "]");
try (Connection con = connectionProvider.get()) {
try (PreparedStatement st = con.prepareStatement(sql)) {
java.sql.ResultSet resultSet = st.executeQuery();
while (resultSet.next()) {
consumer.accept(resultSet);
}
} catch (SQLException e) {
throw new DataAccessException("SQLException whle reading database {} ", e);
}
} catch (SQLException e) {
throw new DataAccessException("SQLException whle connecting to database {} ", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment