> 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/ud8-persistencia-en-bases-de-datos/escenario-de-traballo.md).

# Escenario de traballo

Segue os seguintes paso para montar un escenario de traballo:

1. Crea un **proxecto tipo Maven** e inclue as **dependencias de MariaDB** no pom.xml tal e como se indica no apartado de Anexo:Maven. Lembra empregar a **version 21 de Java**
2. Descarga os **ficheiros docker-compose.yml e Dockerfile** e creaos no directorio principal do proxecto

<figure><img src="/files/2UcgMxSWi8yspudUGcdQ" alt=""><figcaption></figcaption></figure>

3. Na carpeta src/main/resources crea un novo directorio denominado bd e engade nel o seguinte ficheiro init.sql

<figure><img src="/files/qx7UbkxHTDQkGXxGGRk7" alt=""><figcaption></figcaption></figure>

```sql
DROP DATABASE IF EXISTS alumnos;

CREATE DATABASE alumnos;

USE alumnos;

CREATE TABLE departamentos (
    id int unsigned auto_increment PRIMARY KEY,
    nombre VARCHAR(100) NOT NULL,
    presupuesto_anual DECIMAL(12, 2)
);

CREATE TABLE profesores (
    id int unsigned auto_increment PRIMARY KEY,
    nombre VARCHAR(50) NOT NULL,
    email VARCHAR(100) UNIQUE,
    fecha_contrato date NOT NULL,
    id_departamento int unsigned,
    FOREIGN KEY (id_departamento) REFERENCES departamentos(id)
);

CREATE TABLE alumnos (
    id int unsigned auto_increment PRIMARY KEY,
    nombre VARCHAR(50) NOT NULL,
    apellido VARCHAR(50) NOT NULL,
    fechaNac date NOT NULL
);

CREATE TABLE asignaturas (
    id int unsigned auto_increment PRIMARY KEY,
    nombre VARCHAR(80) NOT NULL,
    creditos int,
    curso char,
    id_profesor int unsigned,
    FOREIGN KEY (id_profesor) REFERENCES profesores(id)
);

CREATE TABLE matricula (
    id int unsigned auto_increment PRIMARY KEY,
    anoAcademico VARCHAR(50),
    id_alumno int unsigned,
    id_asignatura int unsigned,
    FOREIGN KEY (id_alumno) REFERENCES alumnos (id)
        ON DELETE RESTRICT ON UPDATE CASCADE,
    FOREIGN KEY (id_asignatura) REFERENCES asignaturas (id)
            ON DELETE RESTRICT ON UPDATE CASCADE
);

CREATE TABLE pagos (
    id int unsigned auto_increment PRIMARY KEY,
    id_alumno int unsigned,
    importe DECIMAL(10, 2) NOT NULL,
    fecha_pago DATETIME NOT NULL, -- Para practicar Timestamp en JDBC
    metodo_pago ENUM('Tarjeta', 'Transferencia', 'Efectivo'),
    FOREIGN KEY (id_alumno) REFERENCES alumnos(id)
);

INSERT INTO departamentos (nombre, presupuesto_anual) VALUES
('Informática y Comunicaciones', 50000.00),
('Formación y Orientación Laboral', 12000.00),
('Idiomas', 8000.00);

INSERT INTO profesores (nombre, email, fecha_contrato, id_departamento) VALUES
('Juan Pérez', 'juan.perez@insti.com', '2015-09-01', 1),
('Maria García', 'm.garcia@insti.com', '2018-10-15', 1),
('Andrés Molina', 'a.molina@insti.com', '2020-01-10', 2),
('Isabel López', 'i.lopez@insti.com', '2022-09-01', 3),
('Ricardo Torres', 'r.torres@insti.com', '2010-05-20', 1);

INSERT INTO asignaturas (nombre, creditos, curso, id_profesor) VALUES
('Programación', 8, '1', 1),
('Lenguaje de Marcas', 5, '1', 2),
('Bases de Datos', 6, '1', 1),
('Sistemas Informáticos', 6, '1', 5),
('Entornos de Desarrollo', 3, '1', 2),
('Formación y Orientación Laboral', 3, '1', 3),
('Inglés Técnico', 2, '1', 4),
('Acceso a Datos', 6, '2', 1),
('Prog. Procesos y Servicios', 6, '2', 5),
('Prog. Multimedia y Móviles', 6, '2', 2),
('Desarrollo de Interfaces', 6, '2', 2),
('Sistemas de Gestión Empresarial', 5, '2', 1),
('Desarrollo Web Entorno Cliente', 6, '2', 5),
('Desarrollo Web Entorno Servidor', 8, '2', 1),
('Despliegue de Aplicaciones Web', 4, '2', 5),
('Diseño de Interfaces Web', 6, '2', 2);

INSERT INTO alumnos (nombre, apellido, fechaNac) VALUES
('Ana', 'García López', '2002-03-15'),
('Carlos', 'Martínez Ruiz', '2001-07-22'),
('Laura', 'Fernández Castro', '2002-11-08'),
('David', 'Rodríguez Molina', '2001-12-30'),
('Sara', 'Gómez Navarro', '2002-05-18'),
('Marcos', 'Pérez Gil', '2003-01-12'),
('Elena', 'Sanz Vega', '2000-09-25');

INSERT INTO matricula (anoAcademico, id_alumno, id_asignatura) VALUES
( '2023-2024', 1, 8),
( '2023-2024', 1, 9),
( '2023-2024', 1, 10), -- Ana en 2º DAM
( '2023-2024', 2, 13),
( '2023-2024', 2, 14),
( '2023-2024', 2, 15), -- Carlos en 2º DAW
( '2023-2024', 3, 1),
( '2023-2024', 3, 3),
( '2023-2024', 3, 6), -- Laura en 1º
( '2023-2024', 4, 1),
( '2023-2024', 4, 3),
( '2023-2024', 4, 4), -- David en 1º
( '2023-2024', 5, 8),
( '2023-2024', 5, 11), -- Sara en 2º DAM
( '2023-2024', 6, 1),
( '2023-2024', 6, 3); -- Marcos en 1º

INSERT INTO pagos (id_alumno, importe, fecha_pago, metodo_pago) VALUES
(1, 150.00, '2023-09-01 10:30:00', 'Tarjeta'),
(1, 150.00, '2024-02-01 11:00:00', 'Transferencia'),
(2, 400.00, '2023-09-05 09:15:00', 'Transferencia'),
(3, 100.00, '2023-09-10 12:00:00', 'Efectivo'),
(3, 100.00, '2023-11-10 12:00:00', 'Efectivo'),
(4, 250.00, '2023-09-12 14:45:00', 'Tarjeta'),
(5, 300.00, '2023-09-15 10:00:00', 'Tarjeta'),
(6, 50.00,  '2023-09-20 08:30:00', 'Efectivo');

-- Concedemos persmisos al usuario
GRANT ALL PRIVILEGES ON alumnos.* TO 'testuser'@'%';
```

4. Na carpeta src/main/resources engade un ficheiro config.properties cos seguintes datos:

<figure><img src="/files/dKdjZcGfFyphUKIowc8P" alt=""><figcaption></figcaption></figure>

```properties
bd.url=jdbc:mariadb://localhost:3306/alumnos
bd.user=testuser
bd.password=testpass
```

5. Dentro da carpeta src/main crea unha nova carpeta nomeada java. Crea os seguintes paquetes na carpeta:
   1. Modelo
   2. DAO
   3. Servicio
   4. Controlador
   5. Vista
   6. Util

Engade a seguinte clase no paquete de Util, que ten por obxecto facilitarnos a lectura do config.properties cos datos do servidor, usuario e contrasinal

```java
package Util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class Lector {

    private static Lector instancia;
    private Properties propiedades;

    private Lector() {
        propiedades = new Properties();
        try (InputStream input = getClass().getClassLoader().getResourceAsStream("config.properties")) {
            if (input == null) {
                System.out.println("Lo siento, no se pudo encontrar config.properties");
                return;
            }
            // Cargamos el archivo de propiedades
            propiedades.load(input);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static synchronized Lector getInstancia() {
        if (instancia == null) {
            instancia = new Lector();
        }
        return instancia;
    }

    public String getValor(String clave) {
        return propiedades.getProperty(clave);
    }

}

```


---

# 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, and the optional `goal` query parameter:

```
GET https://educacion.gitbook.io/programacion/ud8-persistencia-en-bases-de-datos/escenario-de-traballo.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
