public abstract class AbstractController <E, K> { public abstract List<E> getAll(); public abstract E getEntityById(K id); public abstract E update(E entity); public abstract boolean delete(K id); public abstract boolean create(E entity); }
public void closePrepareStatement(PreparedStatement ps) { if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } }
public abstract class AbstractController<E, K> { private Connection connection; private ConnectionPool connectionPool; public AbstractController() { connectionPool = ConnectionPool.getConnectionPool(); connection = connectionPool.getConnection(); } public abstract List<E> getAll(); public abstract E update(E entity); public abstract E getEntityById(K id); public abstract boolean delete(K id); public abstract boolean create(E entity); // Connection public void returnConnectionInPool() { connectionPool.returnConnection(connection); } // PrepareStatement public PreparedStatement getPrepareStatement(String sql) { PreparedStatement ps = null; try { ps = connection.prepareStatement(sql); } catch (SQLException e) { e.printStackTrace(); } return ps; } // PrepareStatement public void closePrepareStatement(PreparedStatement ps) { if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
public class UserController extends AbstractController<User, Integer> { public static final String SELECT_ALL_USERS = "SELECT * FROM SHEMA.USER"; @Override public List<Planet> getAll() { List<User> lst = new LinkedList<>(); PreparedStatement ps = getPrepareStatement(SELECT_ALL_PLANET); try { ResultSet rs = ps.executeQuery(); while (rs.next()) { User user = new User(); planet.setId(rs.getInt(1)); planet.setName(rs.getString(2)); lst.add(user); } } catch (SQLException e) { e.printStackTrace(); } finally { closePrepareStatement(ps); } return lst; } @Override public Planet getEntityById(Integer id) { return null; } @Override public boolean delete(Integer id) { return false; } @Override public boolean create(Planet entity) { return false; } }
public class User implements Serializable { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
Source: https://habr.com/ru/post/262243/
All Articles