package by.bsuir.hypermarket.dao.concrete;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import by.bsuir.hypermarket.connection.DbConnection;
import by.bsuir.hypermarket.connection.DbConnectionPool;
import by.bsuir.hypermarket.connection.exception.ConnectionPoolException;
import by.bsuir.hypermarket.dao.AbstractDao;
import by.bsuir.hypermarket.dao.exception.DaoException;
import by.bsuir.hypermarket.entity.Hypermarket;
public class HypermarketDao extends AbstractDao<Hypermarket> {
private final Logger log = Logger.getLogger(getClass().getSimpleName());
private static final String SQL_FIND_ALL =
"SELECT `h_uid`, `h_phone`, `h_email`, `h_description`"
+ "FROM `hypermarket`";
private static final String SQL_FIND_BY_ID = SQL_FIND_ALL + " WHERE `h_uid` = ?";
@Override
public List<Hypermarket> findAll() throws DaoException {
List<Hypermarket> hypermarkets = new ArrayList<>();
try (DbConnection connection = DbConnectionPool.INSTANCE.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_FIND_ALL)) {
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Hypermarket hypermarket = new Hypermarket();
fillUpHypermarket(resultSet, hypermarket);
hypermarkets.add(hypermarket);
}
} catch (ConnectionPoolException e) {
log.error("Error during getting connection from the pool", e);
throw new DaoException(e);
} catch (SQLException e) {
log.error("Error during searching all address entities", e);
throw new DaoException(e);
}
return hypermarkets;
}
@Override
public Hypermarket findEntityById(int id) throws DaoException {
Hypermarket hypermarket = new Hypermarket();
try (DbConnection connection = DbConnectionPool.INSTANCE.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_FIND_BY_ID)) {
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
fillUpHypermarket(resultSet, hypermarket);
}
} catch (ConnectionPoolException e) {
log.error("Error during getting connection from the pool", e);
throw new DaoException(e);
} catch (SQLException e) {
log.error("Error during searching all address entities", e);
throw new DaoException(e);
}
return hypermarket;
}
private void fillUpHypermarket(ResultSet resultSet, Hypermarket hypermarket) throws SQLException {
hypermarket.setUid(resultSet.getInt("h_uid"));
hypermarket.setPhone(resultSet.getString("h_phone"));
hypermarket.setEmail(resultSet.getString("h_email"));
hypermarket.setDescription(resultSet.getString("h_description"));
}
}