Actividad2.2-Manipulacion datos BBDD-DAO
This commit is contained in:
@@ -0,0 +1,8 @@
|
|||||||
|
# Ignorar la carpeta de compilados
|
||||||
|
bin/
|
||||||
|
*.class
|
||||||
|
|
||||||
|
# Ignorar archivos de configuración de Eclipse
|
||||||
|
.settings/
|
||||||
|
.project
|
||||||
|
.classpath
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>Conectores_02</groupId>
|
||||||
|
<artifactId>Conectores_02</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<!-- aquí metemos las dependencias que tenga el proyecto -->
|
||||||
|
<dependencies>
|
||||||
|
<!-- Source: https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.mysql</groupId>
|
||||||
|
<artifactId>mysql-connector-j</artifactId>
|
||||||
|
<version>26.10.0</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<sourceDirectory>src</sourceDirectory>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.13.0</version>
|
||||||
|
<configuration>
|
||||||
|
<release>26</release>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# Información relativa a la base de datos
|
||||||
|
sgdb.clase.driver=com.mysql.cj.jdbc.Driver
|
||||||
|
sgdb.conexion.url=jdbc:mysql://192.168.1.146:3306/
|
||||||
|
bbdd.nombre=Mapa_Mundi
|
||||||
|
bbdd.usuario=root
|
||||||
|
bbdd.clave=root
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package org.palomafp.aadd.ljl;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.palomafp.aadd.ljl.model.Pais;
|
||||||
|
import org.palomafp.aadd.ljl.service.PaisService;
|
||||||
|
|
||||||
|
public class AppPrincipal {
|
||||||
|
|
||||||
|
private static final int ID_PAIS = 152;
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
AppPrincipal app = new AppPrincipal();
|
||||||
|
|
||||||
|
app.realizarTratamientoPaises();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void realizarTratamientoPaises() {
|
||||||
|
|
||||||
|
PaisService paisService = new PaisService();
|
||||||
|
|
||||||
|
// 1. Imprimir lista Paises
|
||||||
|
List<Pais> listaPaises = paisService.obtenerListaPaises();
|
||||||
|
for (Pais pais : listaPaises) {
|
||||||
|
System.out.println(pais);
|
||||||
|
}
|
||||||
|
System.out.println("----------Fin---obtenerListaPaises-------------");
|
||||||
|
|
||||||
|
// 2. Imprimir país 152
|
||||||
|
Pais pais = paisService.obtenerPaisPorID(ID_PAIS);
|
||||||
|
System.out.println(pais);
|
||||||
|
System.out.println("--------Fin---obtenerPaisPorIdentificador---------------");
|
||||||
|
|
||||||
|
// Se realizan las operaciones si existe el país.
|
||||||
|
if (pais != null) {
|
||||||
|
// 3. Borrar Paises 152
|
||||||
|
paisService.borrarPais(ID_PAIS);
|
||||||
|
System.out.println("--------Fin---borrarPais---------------");
|
||||||
|
|
||||||
|
// 4. Insertar Paises 152
|
||||||
|
paisService.insertarPais(pais);
|
||||||
|
System.out.println("---------Fin---insertarPais--------------");
|
||||||
|
|
||||||
|
// 5. Actualizar País - Capital City
|
||||||
|
pais.setCapital("Capital City");
|
||||||
|
paisService.actualizarPais(pais);
|
||||||
|
System.out.println("---------Fin---actualizarPais--------------");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
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;
|
||||||
|
|
||||||
|
int borrarPais(int identificador) throws SQLException;
|
||||||
|
|
||||||
|
int insertarPais(Pais pais) throws SQLException;
|
||||||
|
|
||||||
|
int actualizarPais(Pais pais) throws SQLException;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
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 {
|
||||||
|
|
||||||
|
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<>();
|
||||||
|
|
||||||
|
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 {
|
||||||
|
|
||||||
|
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 {
|
||||||
|
|
||||||
|
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 {
|
||||||
|
|
||||||
|
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 ------------------
|
||||||
|
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"));
|
||||||
|
}
|
||||||
|
|
||||||
|
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("'", "''");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
|
||||||
|
package org.palomafp.aadd.ljl.gestores;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
|
||||||
|
public class GestorConexionBBDD {
|
||||||
|
|
||||||
|
// Constructor privado: de esta manera conseguimos que esta clase no se puede instanciar.
|
||||||
|
private GestorConexionBBDD() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Connection obtenerConexion() {
|
||||||
|
|
||||||
|
Connection conexion = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Con JDBC 4+ y el driver en el classpath (Maven) DriverManager lo registra solo; Class.forName es redundante.
|
||||||
|
// No es un error, pero puedo quitarlo, el catch de ClassNotFoundException tambien lo quito
|
||||||
|
Class.forName(GestorConfiguracion.getClaseDriver());
|
||||||
|
|
||||||
|
String urlConexionCompleta = GestorConfiguracion.getConexionURL() + GestorConfiguracion.getNombreBBDD();
|
||||||
|
String usuarioBBDD=GestorConfiguracion.getUsuarioBBDD();
|
||||||
|
String claveBBDD=GestorConfiguracion.getClaveBBDD();
|
||||||
|
|
||||||
|
// crear una conexión con la base de datos
|
||||||
|
conexion = DriverManager.getConnection(urlConexionCompleta, usuarioBBDD, claveBBDD);
|
||||||
|
|
||||||
|
} catch (ClassNotFoundException | SQLException e) {
|
||||||
|
throw new RuntimeException("No se ha podido obtener una conexión con el SGDB", e);
|
||||||
|
}
|
||||||
|
return conexion;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package org.palomafp.aadd.ljl.gestores;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
public class GestorConfiguracion {
|
||||||
|
|
||||||
|
private static final String RUTA_FICHERO_CONFIGURACION = "application.properties";
|
||||||
|
private static final Properties PROPIEDADES_CONFIGURACION = new Properties();
|
||||||
|
|
||||||
|
// Constructor privado: de esta manera conseguimos que esta clase no se pueda instanciar.
|
||||||
|
private GestorConfiguracion() {
|
||||||
|
}
|
||||||
|
|
||||||
|
// Este bloque se ejecuta una sola vez, cuando se carga la clase GestorConfiguracion
|
||||||
|
static {
|
||||||
|
try (InputStream inputStream = GestorConfiguracion.class.getClassLoader()
|
||||||
|
.getResourceAsStream(RUTA_FICHERO_CONFIGURACION);) {
|
||||||
|
|
||||||
|
if (inputStream == null) {
|
||||||
|
throw new IOException("No se encuentra " + RUTA_FICHERO_CONFIGURACION + " en el classpath");
|
||||||
|
}
|
||||||
|
PROPIEDADES_CONFIGURACION.load(inputStream);
|
||||||
|
// System.out.println(PROPIEDADES_CONFIGURACION);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException("No se ha podido cargar el fichero de configuración", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public static String getClaseDriver() {
|
||||||
|
return PROPIEDADES_CONFIGURACION.getProperty("sgdb.clase.driver");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getConexionURL() {
|
||||||
|
return PROPIEDADES_CONFIGURACION.getProperty("sgdb.conexion.url");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getNombreBBDD() {
|
||||||
|
return PROPIEDADES_CONFIGURACION.getProperty("bbdd.nombre");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getUsuarioBBDD() {
|
||||||
|
return PROPIEDADES_CONFIGURACION.getProperty("bbdd.usuario");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getClaveBBDD() {
|
||||||
|
return PROPIEDADES_CONFIGURACION.getProperty("bbdd.clave");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package org.palomafp.aadd.ljl.model;
|
||||||
|
|
||||||
|
public class Continente {
|
||||||
|
|
||||||
|
private String codigo;
|
||||||
|
private String nombre;
|
||||||
|
|
||||||
|
// Constructores
|
||||||
|
public Continente() {
|
||||||
|
|
||||||
|
}
|
||||||
|
public Continente(String codigo, String nombre) {
|
||||||
|
super();
|
||||||
|
this.codigo = codigo;
|
||||||
|
this.nombre = nombre;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Getters y setters
|
||||||
|
public String getCodigo() {
|
||||||
|
return codigo;
|
||||||
|
}
|
||||||
|
public String getNombre() {
|
||||||
|
return nombre;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCodigo(String codigo) {
|
||||||
|
this.codigo = codigo;
|
||||||
|
}
|
||||||
|
public void setNombre(String nombre) {
|
||||||
|
this.nombre = nombre;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generamos el método toString
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Continente [codigo=" + codigo + ", nombre=" + nombre + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package org.palomafp.aadd.ljl.model;
|
||||||
|
|
||||||
|
public class Pais {
|
||||||
|
|
||||||
|
private String codContinente;
|
||||||
|
private int identificador;
|
||||||
|
private String nombrePais;
|
||||||
|
private String capital;
|
||||||
|
|
||||||
|
// constructores
|
||||||
|
public Pais(){
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public Pais(String codContinente, int identificador, String nombrePais, String capital) {
|
||||||
|
super();
|
||||||
|
this.codContinente = codContinente;
|
||||||
|
this.identificador = identificador;
|
||||||
|
this.nombrePais = nombrePais;
|
||||||
|
this.capital = capital;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters y setters
|
||||||
|
public String getCodContinente() {
|
||||||
|
return codContinente;
|
||||||
|
}
|
||||||
|
public int getIdentificador() {
|
||||||
|
return identificador;
|
||||||
|
}
|
||||||
|
public String getNombrePais() {
|
||||||
|
return nombrePais;
|
||||||
|
}
|
||||||
|
public String getCapital() {
|
||||||
|
return capital;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCodContinente(String codContinente) {
|
||||||
|
this.codContinente = codContinente;
|
||||||
|
}
|
||||||
|
public void setIdentificador(int identificador) {
|
||||||
|
this.identificador = identificador;
|
||||||
|
}
|
||||||
|
public void setNombrePais(String nombrePais) {
|
||||||
|
this.nombrePais = nombrePais;
|
||||||
|
}
|
||||||
|
public void setCapital(String capital) {
|
||||||
|
this.capital = capital;
|
||||||
|
}
|
||||||
|
|
||||||
|
// sobrescribimos el método toString
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Pais [codContinente=" + codContinente + ", identificador=" + identificador + ", nombrePais="
|
||||||
|
+ nombrePais + ", capital=" + capital + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package org.palomafp.aadd.ljl.service;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.palomafp.aadd.ljl.dao.IPaisDAO;
|
||||||
|
import org.palomafp.aadd.ljl.dao.impl.PaisDaoJDBC;
|
||||||
|
import org.palomafp.aadd.ljl.gestores.GestorConexionBBDD;
|
||||||
|
import org.palomafp.aadd.ljl.model.Pais;
|
||||||
|
|
||||||
|
public class PaisService {
|
||||||
|
|
||||||
|
public List<Pais> obtenerListaPaises() {
|
||||||
|
List<Pais> listaPaises = null;
|
||||||
|
|
||||||
|
try (Connection conexion = GestorConexionBBDD.obtenerConexion();) {
|
||||||
|
|
||||||
|
IPaisDAO iPaisDAO = new PaisDaoJDBC(conexion);
|
||||||
|
listaPaises = iPaisDAO.listarPaises();
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
return listaPaises;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Pais obtenerPaisPorID(int idPais) {
|
||||||
|
|
||||||
|
Pais pais = null;
|
||||||
|
|
||||||
|
try (Connection conexion = GestorConexionBBDD.obtenerConexion();) {
|
||||||
|
|
||||||
|
IPaisDAO iPaisDAO = new PaisDaoJDBC(conexion);
|
||||||
|
pais = iPaisDAO.buscarPaisPorId(idPais);
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
return pais;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void borrarPais(int idPais) {
|
||||||
|
|
||||||
|
try (Connection conexion = GestorConexionBBDD.obtenerConexion()) {
|
||||||
|
|
||||||
|
IPaisDAO iPaisDAO = new PaisDaoJDBC(conexion);
|
||||||
|
|
||||||
|
int filas = iPaisDAO.borrarPais(idPais);
|
||||||
|
|
||||||
|
if (filas>0) {
|
||||||
|
System.out.println("Pais borrado con éxito");
|
||||||
|
}else {
|
||||||
|
System.out.println("No se ha borrado ningun Pais");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertarPais(Pais pais) {
|
||||||
|
|
||||||
|
try (Connection conexion = GestorConexionBBDD.obtenerConexion();) {
|
||||||
|
|
||||||
|
IPaisDAO iPaisDAO = new PaisDaoJDBC(conexion);
|
||||||
|
int filas = iPaisDAO.insertarPais(pais);
|
||||||
|
|
||||||
|
if (filas>0) {
|
||||||
|
System.out.println("Pais insertado con éxito");
|
||||||
|
}else {
|
||||||
|
System.out.println("No se ha insertado ningun Pais");
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void actualizarPais(Pais pais) {
|
||||||
|
|
||||||
|
try (Connection conexion = GestorConexionBBDD.obtenerConexion();) {
|
||||||
|
|
||||||
|
IPaisDAO iPaisDAO = new PaisDaoJDBC(conexion);
|
||||||
|
int filas = iPaisDAO.actualizarPais(pais);
|
||||||
|
|
||||||
|
if (filas>0) {
|
||||||
|
System.out.println("Pais actualizado con éxito");
|
||||||
|
}else {
|
||||||
|
System.out.println("No se ha actualizado ningun Pais");
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
Manifest-Version: 1.0
|
||||||
|
Java-Version: 26
|
||||||
|
Build-Jdk-Spec: 25
|
||||||
|
Created-By: Maven Integration for Eclipse
|
||||||
|
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#Generated by Maven Integration for Eclipse
|
||||||
|
#Mon Nov 02 13:46:09 CET 2026
|
||||||
|
artifactId=Conectores_02
|
||||||
|
groupId=Conectores_02
|
||||||
|
m2e.projectLocation=C\:\\Users\\lauuj\\Desktop\\DAM\\Segundo curso\\Acceso a datos\\workspaceAD\\Conectores_02
|
||||||
|
m2e.projectName=Conectores_02
|
||||||
|
version=0.0.1-SNAPSHOT
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>Conectores_02</groupId>
|
||||||
|
<artifactId>Conectores_02</artifactId>
|
||||||
|
<version>0.0.1-SNAPSHOT</version>
|
||||||
|
|
||||||
|
<!-- aquí metemos las dependencias que tenga el proyecto -->
|
||||||
|
<dependencies>
|
||||||
|
<!-- Source: https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.mysql</groupId>
|
||||||
|
<artifactId>mysql-connector-j</artifactId>
|
||||||
|
<version>26.10.0</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<sourceDirectory>src</sourceDirectory>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.13.0</version>
|
||||||
|
<configuration>
|
||||||
|
<release>26</release>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Información relativa a la base de datos
|
||||||
|
sgdb.clase.driver=com.mysql.cj.jdbc.Driver
|
||||||
|
# REVISION: la URL termina en '/' y el nombre de la BD se concatena en GestorConexionBBDD; funciona, pero es fragil.
|
||||||
|
# Si el driver da problemas de zona horaria/SSL, anade parametros: ?useSSL=false&serverTimezone=UTC
|
||||||
|
sgdb.conexion.url=jdbc:mysql://192.168.1.146:3306/
|
||||||
|
bbdd.nombre=Mapa_Mundi
|
||||||
|
# REVISION: evita root/root. Crea un usuario con permisos solo sobre Mapa_Mundi y no subas este fichero a un repo publico.
|
||||||
|
bbdd.usuario=root
|
||||||
|
bbdd.clave=root
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package org.palomafp.aadd.ljl;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.palomafp.aadd.ljl.model.Pais;
|
||||||
|
import org.palomafp.aadd.ljl.service.PaisService;
|
||||||
|
|
||||||
|
public class AppPrincipal {
|
||||||
|
|
||||||
|
private static final int ID_PAIS = 152;
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
AppPrincipal app = new AppPrincipal();
|
||||||
|
|
||||||
|
app.realizarTratamientoPaises();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void realizarTratamientoPaises() {
|
||||||
|
|
||||||
|
PaisService paisService = new PaisService();
|
||||||
|
|
||||||
|
// 1. Imprimir lista Paises
|
||||||
|
List<Pais> listaPaises = paisService.obtenerListaPaises();
|
||||||
|
// REVISIÓN: si el servicio devuelve null (fallo de BD) esto lanza NullPointerException. Comprueba null o haz que el servicio devuelva lista vacía.
|
||||||
|
for (Pais pais : listaPaises) {
|
||||||
|
System.out.println(pais);
|
||||||
|
}
|
||||||
|
System.out.println("----------Fin---obtenerListaPaises-------------");
|
||||||
|
|
||||||
|
// 2. Imprimir país 152
|
||||||
|
Pais pais = paisService.obtenerPaisPorID(ID_PAIS);
|
||||||
|
System.out.println(pais);
|
||||||
|
System.out.println("--------Fin---obtenerPaisPorIdentificador---------------");
|
||||||
|
|
||||||
|
// Se realizan las operaciones si existe el país.
|
||||||
|
if (pais != null) {
|
||||||
|
// 3. Borrar Paises 152
|
||||||
|
// REVISIÓN: borrar e insertar son dos conexiones/transacciones distintas (cada método del servicio abre la suya).
|
||||||
|
// Si el insert falla, el país 152 se pierde para siempre. Para que sea atómico necesitas una única conexión con
|
||||||
|
// setAutoCommit(false) y commit()/rollback(). Si en la práctica solo se pide esta secuencia, al menos no continúes si el borrado devuelve 0.
|
||||||
|
paisService.borrarPais(ID_PAIS);
|
||||||
|
System.out.println("--------Fin---borrarPais---------------");
|
||||||
|
|
||||||
|
// 4. Insertar Paises 152
|
||||||
|
paisService.insertarPais(pais);
|
||||||
|
System.out.println("---------Fin---insertarPais--------------");
|
||||||
|
|
||||||
|
// 5. Actualizar País - Capital City
|
||||||
|
pais.setCapital("Capital City");
|
||||||
|
paisService.actualizarPais(pais);
|
||||||
|
System.out.println("---------Fin---actualizarPais--------------");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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("'", "''");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
|
||||||
|
package org.palomafp.aadd.ljl.gestores;
|
||||||
|
|
||||||
|
// REVISIÓN: imports sin usar (FileInputStream, IOException y Properties). Quítalos con Ctrl+Shift+O; la lectura del .properties ya la hace GestorConfiguracion.
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.DriverManager;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
public class GestorConexionBBDD {
|
||||||
|
|
||||||
|
// Constructor privado: de esta manera conseguimos que esta clase no se puede instanciar.
|
||||||
|
private GestorConexionBBDD() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Connection obtenerConexion() {
|
||||||
|
|
||||||
|
Connection conexion = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// cargar el driver JDBC -> puede lanzar un ClassNotFoundException
|
||||||
|
// REVISIÓN: con JDBC 4+ y el driver en el classpath (Maven) DriverManager lo registra solo; Class.forName es redundante.
|
||||||
|
// No es un error, pero puedes quitarlo (y con él el ClassNotFoundException y la propiedad sgdb.clase.driver).
|
||||||
|
Class.forName(GestorConfiguracion.getClaseDriver());
|
||||||
|
|
||||||
|
String urlConexionCompleta = GestorConfiguracion.getConexionURL() + GestorConfiguracion.getNombreBBDD();
|
||||||
|
// REVISIÓN (estilo): falta espacio alrededor del '=' en estas dos líneas (usuarioBBDD y claveBBDD).
|
||||||
|
String usuarioBBDD=GestorConfiguracion.getUsuarioBBDD();
|
||||||
|
String claveBBDD=GestorConfiguracion.getClaveBBDD();
|
||||||
|
|
||||||
|
// crear una conexión con la base de datos
|
||||||
|
conexion = DriverManager.getConnection(urlConexionCompleta, usuarioBBDD, claveBBDD);
|
||||||
|
|
||||||
|
} catch (ClassNotFoundException | SQLException e) {
|
||||||
|
throw new RuntimeException("No se ha podido obtener una conexión con el SGDB", e);
|
||||||
|
}
|
||||||
|
return conexion;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package org.palomafp.aadd.ljl.gestores;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
public class GestorConfiguracion {
|
||||||
|
|
||||||
|
private static final String RUTA_FICHERO_CONFIGURACION = "application.properties";
|
||||||
|
private static final Properties PROPIEDADES_CONFIGURACION = new Properties();
|
||||||
|
|
||||||
|
// Constructor privado: de esta manera conseguimos que esta clase no se pueda instanciar.
|
||||||
|
private GestorConfiguracion() {
|
||||||
|
}
|
||||||
|
|
||||||
|
// Este bloque se ejecuta una sola vez, cuando se carga la clase GestorConfiguracion
|
||||||
|
// REVISIÓN: si esto falla, Java lanza ExceptionInInitializerError (envuelve tu RuntimeException) y las llamadas siguientes dan
|
||||||
|
// NoClassDefFoundError, que despista. Funciona, pero ten presente que el mensaje original aparece como 'Caused by'.
|
||||||
|
static {
|
||||||
|
try (InputStream inputStream = GestorConfiguracion.class.getClassLoader()
|
||||||
|
.getResourceAsStream(RUTA_FICHERO_CONFIGURACION);) {
|
||||||
|
|
||||||
|
if (inputStream == null) {
|
||||||
|
throw new IOException("No se encuentra " + RUTA_FICHERO_CONFIGURACION + " en el classpath");
|
||||||
|
}
|
||||||
|
PROPIEDADES_CONFIGURACION.load(inputStream);
|
||||||
|
// System.out.println(PROPIEDADES_CONFIGURACION);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException("No se ha podido cargar el fichero de configuración", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// REVISIÓN: getProperty devuelve null si la clave está mal escrita o falta; el fallo saldría más tarde con un error poco claro.
|
||||||
|
// Podrías validar y lanzar un error que diga qué clave falta.
|
||||||
|
public static String getClaseDriver() {
|
||||||
|
return PROPIEDADES_CONFIGURACION.getProperty("sgdb.clase.driver");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getConexionURL() {
|
||||||
|
return PROPIEDADES_CONFIGURACION.getProperty("sgdb.conexion.url");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getNombreBBDD() {
|
||||||
|
return PROPIEDADES_CONFIGURACION.getProperty("bbdd.nombre");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getUsuarioBBDD() {
|
||||||
|
return PROPIEDADES_CONFIGURACION.getProperty("bbdd.usuario");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getClaveBBDD() {
|
||||||
|
return PROPIEDADES_CONFIGURACION.getProperty("bbdd.clave");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package org.palomafp.aadd.ljl.model;
|
||||||
|
|
||||||
|
public class Continente {
|
||||||
|
|
||||||
|
private String codigo;
|
||||||
|
private String nombre;
|
||||||
|
|
||||||
|
// Constructores
|
||||||
|
public Continente() {
|
||||||
|
|
||||||
|
}
|
||||||
|
public Continente(String codigo, String nombre) {
|
||||||
|
super();
|
||||||
|
this.codigo = codigo;
|
||||||
|
this.nombre = nombre;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Getters y setters
|
||||||
|
public String getCodigo() {
|
||||||
|
return codigo;
|
||||||
|
}
|
||||||
|
public String getNombre() {
|
||||||
|
return nombre;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCodigo(String codigo) {
|
||||||
|
this.codigo = codigo;
|
||||||
|
}
|
||||||
|
public void setNombre(String nombre) {
|
||||||
|
this.nombre = nombre;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generamos el método toString
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Continente [codigo=" + codigo + ", nombre=" + nombre + "]";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package org.palomafp.aadd.ljl.model;
|
||||||
|
|
||||||
|
public class Pais {
|
||||||
|
|
||||||
|
private String codContinente;
|
||||||
|
private int identificador;
|
||||||
|
private String nombrePais;
|
||||||
|
private String capital;
|
||||||
|
|
||||||
|
// constructores
|
||||||
|
public Pais(){
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public Pais(String codContinente, int identificador, String nombrePais, String capital) {
|
||||||
|
super();
|
||||||
|
this.codContinente = codContinente;
|
||||||
|
this.identificador = identificador;
|
||||||
|
this.nombrePais = nombrePais;
|
||||||
|
this.capital = capital;
|
||||||
|
}
|
||||||
|
|
||||||
|
// getters y setters
|
||||||
|
public String getCodContinente() {
|
||||||
|
return codContinente;
|
||||||
|
}
|
||||||
|
public int getIdentificador() {
|
||||||
|
return identificador;
|
||||||
|
}
|
||||||
|
public String getNombrePais() {
|
||||||
|
return nombrePais;
|
||||||
|
}
|
||||||
|
public String getCapital() {
|
||||||
|
return capital;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCodContinente(String codContinente) {
|
||||||
|
this.codContinente = codContinente;
|
||||||
|
}
|
||||||
|
public void setIdentificador(int identificador) {
|
||||||
|
this.identificador = identificador;
|
||||||
|
}
|
||||||
|
public void setNombrePais(String nombrePais) {
|
||||||
|
this.nombrePais = nombrePais;
|
||||||
|
}
|
||||||
|
public void setCapital(String capital) {
|
||||||
|
this.capital = capital;
|
||||||
|
}
|
||||||
|
|
||||||
|
// sobrescribimos el método toString
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return "Pais [codContinente=" + codContinente + ", identificador=" + identificador + ", nombrePais="
|
||||||
|
+ nombrePais + ", capital=" + capital + "]";
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package org.palomafp.aadd.ljl.service;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.palomafp.aadd.ljl.dao.IPaisDAO;
|
||||||
|
import org.palomafp.aadd.ljl.dao.impl.PaisDaoJDBC;
|
||||||
|
import org.palomafp.aadd.ljl.gestores.GestorConexionBBDD;
|
||||||
|
import org.palomafp.aadd.ljl.model.Pais;
|
||||||
|
|
||||||
|
public class PaisService {
|
||||||
|
|
||||||
|
public List<Pais> obtenerListaPaises() {
|
||||||
|
// REVISIÓN: inicializar a null y devolverlo tras un fallo obliga a quien llama a comprobar null (AppPrincipal no lo hace).
|
||||||
|
// Mejor devolver una lista vacía (new ArrayList<>() / List.of()) o dejar que la excepción suba.
|
||||||
|
List<Pais> listaPaises = null;
|
||||||
|
|
||||||
|
try (Connection conexion = GestorConexionBBDD.obtenerConexion();) {
|
||||||
|
|
||||||
|
IPaisDAO iPaisDAO = new PaisDaoJDBC(conexion);
|
||||||
|
listaPaises = iPaisDAO.listarPaises();
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
// REVISIÓN: printStackTrace() se traga el error. Si falla la consulta, el método devuelve null y AppPrincipal lanza
|
||||||
|
// NullPointerException en el for. Relanza una excepción propia (p. ej. throw new RuntimeException("...", e)) o devuelve lista vacía.
|
||||||
|
// Este mismo patrón se repite en todos los métodos del servicio.
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
return listaPaises;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Pais obtenerPaisPorID(int idPais) {
|
||||||
|
|
||||||
|
Pais pais = null;
|
||||||
|
|
||||||
|
try (Connection conexion = GestorConexionBBDD.obtenerConexion();) {
|
||||||
|
|
||||||
|
IPaisDAO iPaisDAO = new PaisDaoJDBC(conexion);
|
||||||
|
pais = iPaisDAO.buscarPaisPorId(idPais);
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
return pais;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void borrarPais(int idPais) {
|
||||||
|
|
||||||
|
try (Connection conexion = GestorConexionBBDD.obtenerConexion()) {
|
||||||
|
|
||||||
|
IPaisDAO iPaisDAO = new PaisDaoJDBC(conexion);
|
||||||
|
// REVISIÓN: ignoras el int que devuelve el DAO (filas afectadas). Si es 0 (el país no existía) igualmente imprimes 'éxito'.
|
||||||
|
// Haz: int filas = iPaisDAO.borrarPais(idPais); y muestra el mensaje solo si filas > 0.
|
||||||
|
iPaisDAO.borrarPais(idPais);
|
||||||
|
System.out.println("Pais borrado con éxito");
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertarPais(Pais pais) {
|
||||||
|
|
||||||
|
try (Connection conexion = GestorConexionBBDD.obtenerConexion();) {
|
||||||
|
|
||||||
|
IPaisDAO iPaisDAO = new PaisDaoJDBC(conexion);
|
||||||
|
// REVISIÓN: comprueba el int devuelto (filas insertadas) antes de imprimir 'éxito', igual que en borrarPais.
|
||||||
|
iPaisDAO.insertarPais(pais);
|
||||||
|
System.out.println("Pais insertado con éxito");
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void actualizarPais(Pais pais) {
|
||||||
|
|
||||||
|
try (Connection conexion = GestorConexionBBDD.obtenerConexion();) {
|
||||||
|
|
||||||
|
IPaisDAO iPaisDAO = new PaisDaoJDBC(conexion);
|
||||||
|
// REVISIÓN: comprueba el int devuelto; si es 0 no existía ese identificador y no se ha actualizado nada.
|
||||||
|
iPaisDAO.actualizarPais(pais);
|
||||||
|
System.out.println("Pais actualizado con éxito");
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user