package io.trygvis.persistence.sql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public abstract class SqlDao { protected final S session; protected SqlDao(S session) { this.session = session; } public abstract void insert(T o) throws SQLException; public abstract void delete(T o) throws SQLException; public abstract void deleteById(Id id) throws SQLException; public abstract T selectById(Id id) throws SQLException; public abstract void update(T entity) throws SQLException; public abstract List selectWhere(String where) throws SQLException; public abstract String[] createTableSql(); // ----------------------------------------------------------------------- // Protected // ----------------------------------------------------------------------- protected abstract Row newRow(ResultSet rs) throws SQLException; protected abstract T newEntity(Row row) throws SQLException; protected List runQuery(final String sql) throws SQLException { return runQuery(new Preparator() { @Override public void prepare(PreparedStatement stmt) throws SQLException { } }, sql); } protected List runQuery(final Preparator preparator, final String sql) throws SQLException { return session.query(new SqlExecutor.QueryCommand() { @Override public List run(Connection c) throws SQLException { try (PreparedStatement stmt = c.prepareStatement(sql)) { preparator.prepare(stmt); ResultSet rs = stmt.executeQuery(); List rows = new ArrayList<>(); while (rs.next()) { rows.add(newRow(rs)); } List entities = new ArrayList<>(rows.size()); for (Row row : rows) { entities.add(newEntity(row)); } return entities; } } }); } protected static interface Preparator { void prepare(PreparedStatement stmt) throws SQLException; } }