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.Country;
public class CountryDao extends AbstractDao<Country> {
private final Logger log = Logger.getLogger(getClass().getSimpleName());
private static final String SQL_FIND_ALL = "SELECT `country_uid`, `country_name` FROM `country`";
private static final String SQL_FIND_BY_ID = SQL_FIND_ALL + " WHERE `country_uid` = ?";
@Override
public List<Country> findAll() throws DaoException {
List<Country> countries = new ArrayList<Country>();
try (DbConnection connection = DbConnectionPool.INSTANCE.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_FIND_ALL)){
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Country country = new Country();
fillUpCountry(resultSet, country);
countries.add(country);
}
} catch (SQLException e) {
log.error("Error during statement creation", e);
throw new DaoException(e);
} catch (ConnectionPoolException e) {
log.error("Error during getting connection from the pool", e);
throw new DaoException(e);
}
return countries;
}
@Override
public Country findEntityById(int id) throws DaoException {
Country country = new Country();
try (DbConnection connection = DbConnectionPool.INSTANCE.getConnection();
PreparedStatement idStatement = connection.prepareStatement(SQL_FIND_BY_ID)) {
idStatement.setInt(1, id);
ResultSet resultSet = idStatement.executeQuery();
if (resultSet.next()) {
fillUpCountry(resultSet, country);
}
} catch (SQLException e) {
log.error("Error during statement creation", e);
throw new DaoException(e);
} catch (ConnectionPoolException e) {
log.error("Error during getting connection from the pool", e);
throw new DaoException(e);
}
return country;
}
private void fillUpCountry(ResultSet resultSet, Country country) throws SQLException {
country.setUid(resultSet.getInt("country_uid"));
country.setName(resultSet.getString("country_name"));
}
}