Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.