> For the complete documentation index, see [llms.txt](https://educacion.gitbook.io/programacion/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://educacion.gitbook.io/programacion/exercicios-java/ud8-solucions/modelo-e-dao-con-statement.md).

# Modelo e DAO con Statement

Modelo Profesor

```java
package Modelo;

import java.time.LocalDate;

public class Profesor {
   private int id;
   private String nombre;
   private String email;
   private LocalDate fechaContrato;
   private int idDepartamento;

    public Profesor() {
    }

    public Profesor(int id, String nombre, String email, LocalDate fechaContrato, int idDepartamento) {
        this.id = id;
        this.nombre = nombre;
        this.email = email;
        this.fechaContrato = fechaContrato;
        this.idDepartamento = idDepartamento;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public LocalDate getFechaContrato() {
        return fechaContrato;
    }

    public void setFechaContrato(LocalDate fechaContrato) {
        this.fechaContrato = fechaContrato;
    }

    public int getIdDepartamento() {
        return idDepartamento;
    }

    public void setIdDepartamento(int idDepartamento) {
        this.idDepartamento = idDepartamento;
    }

    @Override
    public String toString() {
        return "Profesor{" +
                "id=" + id +
                ", nombre='" + nombre + '\'' +
                ", email='" + email + '\'' +
                ", fechaContrato=" + fechaContrato +
                ", idDepartamento=" + idDepartamento +
                '}';
    }
}

```

DAO con Statement

```java
package DAO;

import Util.Lector;
import Modelo.Profesor;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class ProfesorDAOImpl {

    public List<Profesor> findAll() {
        List<Profesor> lista = new ArrayList<>();
        String sql = "SELECT * FROM profesores";
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             Statement s = con.createStatement()){
            ResultSet rs = s.executeQuery(sql);
            while (rs.next()){
                /*Profesor profesor = new Profesor(
                        rs.getInt("id"),
                        rs.getString("nombre"),
                        rs.getString("email"),
                        rs.getDate("fecha_contrato").toLocalDate(),
                        rs.getInt("id_departamento")
                );*/
                Profesor profesor = new Profesor(
                        rs.getInt(1),
                        rs.getString(2),
                        rs.getString(3),
                        rs.getDate(4).toLocalDate(),
                        rs.getInt(5)
                );
                lista.add(profesor);
            }

        } catch (SQLException e){
            System.out.println(e.getMessage());
        }
        return lista;
    }


    public Optional<Profesor> findById(int id) {
        Optional<Profesor> res;
        String sql = "SELECT * FROM profesores WHERE id = " + id;
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             Statement s = con.createStatement()){
            ResultSet rs = s.executeQuery(sql);

            if (rs.next()){
                Profesor profesor = new Profesor(
                        rs.getInt("id"),
                        rs.getString("nombre"),
                        rs.getString("email"),
                        rs.getDate("fecha_contrato").toLocalDate(),
                        rs.getInt("id_departamento")
                );
                res = Optional.of(profesor);
                return res;
            }

        } catch (SQLException e){
            System.out.println(e.getMessage());
        }
        return Optional.empty();
    }

    public int insert(Profesor p) {
        String sql = "INSERT INTO profesores (nombre, email, fecha_contrato, id_departamento) VALUES (" +
                "'" + p.getNombre() + "', " +
                "'" + p.getEmail() + "', " +
                "'" + p.getFechaContrato().toString() + "', " +
                p.getIdDepartamento() + ")";
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             Statement s = con.createStatement()) {

            int filasAfectadas = s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);

            if (filasAfectadas > 0) {
                ResultSet rs = s.getGeneratedKeys();
                if (rs.next()) {
                    int id = rs.getInt(1);
                    p.setId(id);
                    return id;
                }
                return -1;
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return -1;
    }

    public Optional<Profesor> update(Profesor p) {
        String sql = "UPDATE profesores SET " +
                "nombre = '" + p.getNombre() + "', " +
                "email = '" + p.getEmail() + "', " +
                "fecha_contrato = '" + p.getFechaContrato().toString() + "', " +
                "id_departamento = " + p.getIdDepartamento() + " " +
                "WHERE id = " + p.getId();
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             Statement s = con.createStatement()) {

            int filasAfectadas = s.executeUpdate(sql);
            if (filasAfectadas > 0) {
                return Optional.of(p);
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return Optional.empty();
    }

    public boolean remove(int id) {
        String sql = "DELETE FROM profesores WHERE id = " + id;
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             Statement s = con.createStatement()) {
            int filasAfectadas = s.executeUpdate(sql);
            return filasAfectadas > 0;

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return false;

    }
}

```

App

```java
 ProfesorDAOPrepStat profesorDAO = new ProfesorDAOPrepStat();

        // 1. LISTAR TODOS
        List<Profesor> profesores = profesorDAO.findAll();
        System.out.println("===TODOS LOS PROFESORES===");
        for (Profesor p : profesores) {
            System.out.println(p);
        }

        // 2. INSERTAR
        System.out.println("===INSERTAR===");
        // Suponemos id_departamento = 1 (asegúrate de que existe en tu tabla departamentos)
        Profesor nuevoP = new Profesor(0, "Carlos", "carlos@edu.es", LocalDate.of(2020, 9, 1), 1);
        nuevoId = profesorDAO.insert(nuevoP);

        if (nuevoId != -1) {
            System.out.println("Profesor insertado con éxito. ID asignado: " + nuevoId);
        } else {
            System.out.println("Error al insertar profesor.");
        }

        // 3. BUSCAR POR ID
        System.out.println("===BUSCAR POR ID===");
        System.out.println("ID: " + nuevoId);
        Optional<Profesor> profesorBuscado = profesorDAO.findById(nuevoId);

        if (profesorBuscado.isPresent()) {
            System.out.println("Profesor recuperado con éxito: " + profesorBuscado.get());
        } else {
            System.out.println("Error al recuperar profesor.");
        }

        // 4. ACTUALIZAR
        System.out.println("===ACTUALIZAR===");
        if (profesorBuscado.isPresent()) {
            Profesor profActualizar = profesorBuscado.get();
            profActualizar.setNombre("Carlos Modificado");
            profActualizar.setEmail("carlos.mod@edu.es");

            Optional<Profesor> actualizadoP = profesorDAO.update(profActualizar);
            if (actualizadoP.isPresent()) {
                System.out.println("Profesor actualizado con éxito: " + actualizadoP.get());
            } else {
                System.out.println("Error al actualizar profesor.");
            }
        }

        // 5. BORRAR
        System.out.println("===BORRAR===");
        boolean eliminadoP = profesorDAO.remove(nuevoId);
        if (eliminado) {
            System.out.println("Profesor con ID " + nuevoId + " eliminado correctamente.");
        } else {
            System.out.println("No se pudo eliminar el profesor.");
        }
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://educacion.gitbook.io/programacion/exercicios-java/ud8-solucions/modelo-e-dao-con-statement.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
