Actividad2.2-Manipulacion datos BBDD-DAO
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
package org.palomafp.aadd.ljl.dao;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
import org.palomafp.aadd.ljl.model.Pais;
|
||||
|
||||
public interface IPaisDAO {
|
||||
|
||||
List<Pais> listarPaises() throws SQLException;
|
||||
|
||||
Pais buscarPaisPorId(int identificador) throws SQLException;
|
||||
|
||||
// REVISIÓN: documenta con Javadoc que los int devueltos son las 'filas afectadas'; el servicio debería usarlos (ver PaisService).
|
||||
int borrarPais(int identificador) throws SQLException;
|
||||
|
||||
int insertarPais(Pais pais) throws SQLException;
|
||||
|
||||
int actualizarPais(Pais pais) throws SQLException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package org.palomafp.aadd.ljl.dao.impl;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.palomafp.aadd.ljl.dao.IPaisDAO;
|
||||
import org.palomafp.aadd.ljl.model.Pais;
|
||||
|
||||
public class PaisDaoJDBC implements IPaisDAO {
|
||||
|
||||
// REVISIÓN: el DAO recibe la conexión de fuera (bien), pero luego la CIERRA él mismo con try (Connection con = conexionDB).
|
||||
// La conexión pertenece a quien la abre (PaisService, que ya la cierra en su try-with-resources). Aquí se cierra dos veces
|
||||
// y, sobre todo, este DAO solo sirve para UNA operación: una segunda llamada fallaría con 'connection closed'.
|
||||
// Solución: usa try (Statement st = conexionDB.createStatement(); ResultSet rs = ...) y no cierres la conexión en el DAO.
|
||||
private final Connection conexionDB;
|
||||
|
||||
public PaisDaoJDBC(Connection conexionDB) {
|
||||
this.conexionDB = conexionDB;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Pais> listarPaises() throws SQLException {
|
||||
String sql = "SELECT cod_continente, identificador, nombre_pais, capital FROM T_PAIS";
|
||||
List<Pais> paises = new ArrayList<>();
|
||||
|
||||
// REVISIÓN: no cierres aquí la conexión (ver comentario del atributo conexionDB). Se repite en todos los métodos.
|
||||
try (Connection con = conexionDB;
|
||||
Statement st = con.createStatement();
|
||||
ResultSet rs = st.executeQuery(sql)) {
|
||||
|
||||
while (rs.next()) {
|
||||
paises.add(mapear(rs));
|
||||
}
|
||||
}
|
||||
return paises;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Pais buscarPaisPorId(int identificador) throws SQLException {
|
||||
// REVISIÓN: el int concatenado no es inyectable, pero por coherencia usa PreparedStatement con '?' en todo el DAO
|
||||
// (ps.setInt(1, identificador)). Además la BD cachea y reutiliza mejor la consulta.
|
||||
String sql = "SELECT cod_continente, identificador, nombre_pais, capital "
|
||||
+ "FROM T_PAIS WHERE identificador = " + identificador;
|
||||
|
||||
try (Connection con = conexionDB;
|
||||
Statement st = con.createStatement();
|
||||
ResultSet rs = st.executeQuery(sql)) {
|
||||
|
||||
if (rs.next()) {
|
||||
return mapear(rs);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int borrarPais(int identificador) throws SQLException {
|
||||
String sql = "DELETE FROM T_PAIS WHERE identificador = " + identificador;
|
||||
|
||||
try (Connection con = conexionDB;
|
||||
Statement st = con.createStatement()) {
|
||||
return st.executeUpdate(sql);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int insertarPais(Pais pais) throws SQLException {
|
||||
// REVISIÓN: concatenar textos en el SQL es vulnerable a SQL injection aunque uses escapar(), y es frágil.
|
||||
// Usa PreparedStatement: "INSERT INTO T_PAIS (cod_continente, identificador, nombre_pais, capital) VALUES (?, ?, ?, ?)"
|
||||
// con ps.setString(1, ...), ps.setInt(2, ...), etc. Con eso ya no necesitas el método escapar().
|
||||
String sql = "INSERT INTO T_PAIS (cod_continente, identificador, nombre_pais, capital) VALUES ("
|
||||
+ "'" + escapar(pais.getCodContinente()) + "', "
|
||||
+ pais.getIdentificador() + ", "
|
||||
+ "'" + escapar(pais.getNombrePais()) + "', "
|
||||
+ "'" + escapar(pais.getCapital()) + "')";
|
||||
|
||||
try (Connection con = conexionDB;
|
||||
Statement st = con.createStatement()) {
|
||||
return st.executeUpdate(sql);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int actualizarPais(Pais pais) throws SQLException {
|
||||
// REVISIÓN: igual que en insertarPais -> PreparedStatement: "UPDATE T_PAIS SET cod_continente = ?, nombre_pais = ?, capital = ? WHERE identificador = ?".
|
||||
String sql = "UPDATE T_PAIS SET "
|
||||
+ "cod_continente = '" + escapar(pais.getCodContinente()) + "', "
|
||||
+ "nombre_pais = '" + escapar(pais.getNombrePais()) + "', "
|
||||
+ "capital = '" + escapar(pais.getCapital()) + "' "
|
||||
+ "WHERE identificador = " + pais.getIdentificador();
|
||||
|
||||
try (Connection con = conexionDB;
|
||||
Statement st = con.createStatement()) {
|
||||
return st.executeUpdate(sql);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------ MÉTODOS AUXILIARES ------------------
|
||||
// REVISIÓN (estilo): la línea 'return new Pais(' mezcla tabulador y espacios; en Eclipse usa Ctrl+Shift+F para formatear.
|
||||
private Pais mapear(ResultSet rs) throws SQLException {
|
||||
// cuidado debe coincidir con el orden del constructor de Pais
|
||||
return new Pais(
|
||||
rs.getString("cod_continente"),
|
||||
rs.getInt("identificador"),
|
||||
rs.getString("nombre_pais"),
|
||||
rs.getString("capital"));
|
||||
}
|
||||
|
||||
// Escapa comillas simples y barras invertidas al concatenar con Statement
|
||||
// REVISIÓN: si texto es null devuelves "", así que guardarías una cadena vacía en lugar de NULL en la BD.
|
||||
// Además, escapar a mano depende del modo SQL del servidor (p. ej. NO_BACKSLASH_ESCAPES lo rompe).
|
||||
// Con PreparedStatement este método sobra (y ps.setString(i, null) / setNull guarda un NULL real).
|
||||
private String escapar(String texto) {
|
||||
if (texto == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// le estamos diciendo que \ -> \\ (escapamos cada barra en java) | y que la ' -> ''
|
||||
// porque l'aura -> sera 'l''aura' y eso no rompe la cadena ('l'aura') si que la romperia
|
||||
// 'Capital\' escapria la comilla y el texto seguiria -> 'Capital\\' escapa la barra
|
||||
return texto.replace("\\", "\\\\").replace("'", "''");
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user