Advertisement
goosegle

Ejemplo de DAO para JavaDB

Jan 26th, 2019
314
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.48 KB | None | 0 0
  1. package paquete.dao;
  2.  
  3. import paquete.model.Entidad;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.logging.Level;
  12. import java.util.logging.Logger;
  13.  
  14. /**
  15.  * Define el Data Access Object para comunicación con la base de datos para las
  16.  * operaciones relativas a Entidad. No contempla transacciones.
  17.  */
  18. public class EntidadDao {
  19.     // URL para el acceso a la base de datos.
  20.     private static final String DB_URL = "jdbc:derby://localhost:1527/NombreDB;user=usuario;password=password";
  21.    
  22.     /**
  23.      * Obtiene todas las entidades de la base de datos.
  24.      * @return  Lista de entidades.
  25.      * @throws ClassNotFoundException
  26.      */
  27.     public List<Entidad> findAll() throws ClassNotFoundException {
  28.         Connection con = null;
  29.         List<Entidad> result = new ArrayList<>();
  30.        
  31.         try {
  32.             Class.forName("org.apache.derby.jdbc.ClientDriver");
  33.             con = DriverManager.getConnection(DB_URL);
  34.             PreparedStatement stmt = con.prepareStatement("select * from Entidades");
  35.  
  36.             ResultSet rs = stmt.executeQuery();
  37.             // Se recorre el conjunto de resultados para añadir la información a
  38.             // una instancia de entidad que se guardará en la lista.
  39.             while(rs.next()) {
  40.                 result.add(new Entidad(rs.getInt("id"), rs.getString("nombre")));
  41.             }
  42.         } catch (SQLException ex) {
  43.             // Añade al log el error y devuelve una lista vacía.
  44.             Logger.getLogger(EntidadDao.class.getName()).log(Level.SEVERE, null, ex);
  45.         }
  46.         finally {
  47.             // Se intenta cerrar la conexión.
  48.             try {
  49.                 if(con != null && !con.isClosed())
  50.                     con.close();
  51.             } catch (SQLException ex) {
  52.                 Logger.getLogger(EntidadDao.class.getName()).log(Level.WARNING, null, ex);
  53.             }
  54.         }
  55.        
  56.         return result;
  57.     }
  58.    
  59.     /**
  60.      * Añade una nueva entidad a la base de datos.
  61.      * @param entidad   entidad que se añadirá.
  62.      * @throws ClassNotFoundException
  63.      */
  64.     public void insert(Entidad entidad) throws ClassNotFoundException {
  65.         Connection con = null;
  66.  
  67.         try {
  68.             Class.forName("org.apache.derby.jdbc.ClientDriver");
  69.             con = DriverManager.getConnection(DB_URL);
  70.             try (PreparedStatement stmt = con.prepareStatement("insert into entidades(id, nombre) values(?,?)")) {
  71.                 stmt.setInt(1, entidad.getId());
  72.                 stmt.setString(2, entidad.getNombre());
  73.                 stmt.executeUpdate();
  74.             }
  75.         } catch (SQLException ex) {
  76.             Logger.getLogger(EntidadDao.class.getName()).log(Level.SEVERE, ex.getSQLState(), ex);
  77.             throw new RuntimeException(ex.getMessage());
  78.         }
  79.         finally {
  80.             try {
  81.                 if(con != null && !con.isClosed())
  82.                     con.close();
  83.             } catch (SQLException ex) {
  84.                 Logger.getLogger(EntidadDao.class.getName()).log(Level.WARNING, null, ex);
  85.             }
  86.         }
  87.     }
  88.    
  89.     /**
  90.      * Actualiza una entidad de la base de datos.
  91.      * @param entidad   entidad que se actualizará.
  92.      * @throws ClassNotFoundException
  93.      */
  94.     public void update(Entidad entidad) throws ClassNotFoundException {
  95.         Connection con = null;
  96.  
  97.         try {
  98.             Class.forName("org.apache.derby.jdbc.ClientDriver");
  99.             con = DriverManager.getConnection(DB_URL);
  100.             try (PreparedStatement stmt = con.prepareStatement("update entidades set nombre = ? where id = ?")) {
  101.                 stmt.setString(1, entidad.getNombre());
  102.                 stmt.setInt(2, entidad.getId());
  103.                 stmt.executeUpdate();
  104.             }
  105.         } catch (SQLException ex) {
  106.             Logger.getLogger(EntidadDao.class.getName()).log(Level.SEVERE, ex.getSQLState(), ex);
  107.             throw new RuntimeException(ex.getMessage());
  108.         }
  109.         finally {
  110.             try {
  111.                 if(con != null && !con.isClosed())
  112.                     con.close();
  113.             } catch (SQLException ex) {
  114.                 Logger.getLogger(EntidadDao.class.getName()).log(Level.WARNING, null, ex);
  115.             }
  116.         }
  117.     }
  118.    
  119.     /**
  120.      * Borra una entidad de la base de datos.
  121.      * @param entidad   entidad que se borrará.
  122.      * @throws ClassNotFoundException
  123.      */
  124.     public void delete(Entidad entidad) throws ClassNotFoundException {
  125.         Connection con = null;
  126.  
  127.         try {
  128.             Class.forName("org.apache.derby.jdbc.ClientDriver");
  129.             con = DriverManager.getConnection(DB_URL);
  130.             try (PreparedStatement stmt = con.prepareStatement("delete from entidades where id = ?")) {
  131.                 stmt.setInt(1, entidad.getId());
  132.                 stmt.executeUpdate();
  133.             }
  134.         } catch (SQLException ex) {
  135.             Logger.getLogger(EntidadDao.class.getName()).log(Level.SEVERE, ex.getSQLState(), ex);
  136.             throw new RuntimeException(ex.getMessage());
  137.         }
  138.         finally {
  139.             try {
  140.                 if(con != null && !con.isClosed())
  141.                     con.close();
  142.             } catch (SQLException ex) {
  143.                 Logger.getLogger(EntidadDao.class.getName()).log(Level.WARNING, null, ex);
  144.             }
  145.         }
  146.     }
  147. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement