Skip to content

Instantly share code, notes, and snippets.

@rattanchauhan
Last active December 9, 2018 12:15
Show Gist options
  • Save rattanchauhan/47073362ba1cafc5437ef8227296f534 to your computer and use it in GitHub Desktop.
Save rattanchauhan/47073362ba1cafc5437ef8227296f534 to your computer and use it in GitHub Desktop.
Simple Jdbc Template with datasource in Java 8
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import app.example.exception.DataAccessException;
import javax.sql.DataSource;
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;
public class JdbcTemplate {
private DataSource dataSource;
public JdbcTemplate(DataSource dataSource) {
this.dataSource = dataSource;
}
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 = dataSource.getConnection()) {
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 = dataSource.getConnection()) {
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);
}
}
public <R> R queryWithParams(final String sql, String[] params, final Function<ResultSet, R> mapper) {
LOG.info("Executing SQL query [" + sql + "]");
try (Connection con = dataSource.getConnection()) {
try (PreparedStatement st = con.prepareStatement(sql)) {
for (int i = 0; i < params.length; i++) {
st.setString(i + 1, params[i]);
}
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);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment