package paquete.dao;
import paquete.model.Entidad;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Define el Data Access Object para comunicación con la base de datos para las
* operaciones relativas a Entidad. No contempla transacciones.
*/
public class EntidadDao {
// URL para el acceso a la base de datos.
private static final String DB_URL = "jdbc:derby://localhost:1527/NombreDB;user=usuario;password=password";
/**
* Obtiene todas las entidades de la base de datos.
* @return Lista de entidades.
* @throws ClassNotFoundException
*/
public List<Entidad> findAll() throws ClassNotFoundException {
Connection con = null;
List<Entidad> result = new ArrayList<>();
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(DB_URL);
PreparedStatement stmt = con.prepareStatement("select * from Entidades");
ResultSet rs = stmt.executeQuery();
// Se recorre el conjunto de resultados para añadir la información a
// una instancia de entidad que se guardará en la lista.
while(rs.next()) {
result.add(new Entidad(rs.getInt("id"), rs.getString("nombre")));
}
} catch (SQLException ex) {
// Añade al log el error y devuelve una lista vacía.
Logger.getLogger(EntidadDao.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
// Se intenta cerrar la conexión.
try {
if(con != null && !con.isClosed())
con.close();
} catch (SQLException ex) {
Logger.getLogger(EntidadDao.class.getName()).log(Level.WARNING, null, ex);
}
}
return result;
}
/**
* Añade una nueva entidad a la base de datos.
* @param entidad entidad que se añadirá.
* @throws ClassNotFoundException
*/
public void insert(Entidad entidad) throws ClassNotFoundException {
Connection con = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(DB_URL);
try (PreparedStatement stmt = con.prepareStatement("insert into entidades(id, nombre) values(?,?)")) {
stmt.setInt(1, entidad.getId());
stmt.setString(2, entidad.getNombre());
stmt.executeUpdate();
}
} catch (SQLException ex) {
Logger.getLogger(EntidadDao.class.getName()).log(Level.SEVERE, ex.getSQLState(), ex);
throw new RuntimeException(ex.getMessage());
}
finally {
try {
if(con != null && !con.isClosed())
con.close();
} catch (SQLException ex) {
Logger.getLogger(EntidadDao.class.getName()).log(Level.WARNING, null, ex);
}
}
}
/**
* Actualiza una entidad de la base de datos.
* @param entidad entidad que se actualizará.
* @throws ClassNotFoundException
*/
public void update(Entidad entidad) throws ClassNotFoundException {
Connection con = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(DB_URL);
try (PreparedStatement stmt = con.prepareStatement("update entidades set nombre = ? where id = ?")) {
stmt.setString(1, entidad.getNombre());
stmt.setInt(2, entidad.getId());
stmt.executeUpdate();
}
} catch (SQLException ex) {
Logger.getLogger(EntidadDao.class.getName()).log(Level.SEVERE, ex.getSQLState(), ex);
throw new RuntimeException(ex.getMessage());
}
finally {
try {
if(con != null && !con.isClosed())
con.close();
} catch (SQLException ex) {
Logger.getLogger(EntidadDao.class.getName()).log(Level.WARNING, null, ex);
}
}
}
/**
* Borra una entidad de la base de datos.
* @param entidad entidad que se borrará.
* @throws ClassNotFoundException
*/
public void delete(Entidad entidad) throws ClassNotFoundException {
Connection con = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(DB_URL);
try (PreparedStatement stmt = con.prepareStatement("delete from entidades where id = ?")) {
stmt.setInt(1, entidad.getId());
stmt.executeUpdate();
}
} catch (SQLException ex) {
Logger.getLogger(EntidadDao.class.getName()).log(Level.SEVERE, ex.getSQLState(), ex);
throw new RuntimeException(ex.getMessage());
}
finally {
try {
if(con != null && !con.isClosed())
con.close();
} catch (SQLException ex) {
Logger.getLogger(EntidadDao.class.getName()).log(Level.WARNING, null, ex);
}
}
}
}
Comments