Saltar al contenido principal

TP2.2 - Base de Datos H2

Objetivos​

  • Comprender la diferencia entre base de datos en memoria y persistente
  • Crear una entidad JPA y un repository
  • Utilizar los 4 métodos CRUD básicos (save, findById, findAll, deleteById)
  • Acceder a la consola H2

Parte 1: H2 en Memoria (Datos Temporales)​

1.1 Creación del Proyecto​

Ir a: https://start.spring.io/

Configuración:

  • Project: Maven
  • Language: Java
  • Spring Boot: 3.2.0+
  • Group: com.example
  • Artifact: h2-memoire
  • Java: 17

Dependencias:

  • Spring Web
  • H2 Database
  • Spring Data JPA

Genere y descomprima en su workspace.


1.2 Crear la Entidad Employee​

Archivo: src/main/java/com/example/h2memoire/model/Employee.java

package com.example.h2memoire.model;

import jakarta.persistence.*;

@Entity
@Table(name = "tbl_employees")
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String firstName;
private String lastName;
private String email;

// Constructeurs
public Employee() {
}

public Employee(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

// Getters et Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }

public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }

public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }

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

1.3 Crear el Repository​

Archivo: src/main/java/com/example/h2memoire/repository/EmployeeRepository.java

package com.example.h2memoire.repository;

import com.example.h2memoire.model.Employee;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
// Méthodes héritées: save(), findById(), findAll(), deleteById()
}

1.4 Configuración​

Archivo: src/main/resources/application.properties

# Console H2
spring.h2.console.enabled=true

# Base de datos en MEMORIA
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# Hibernate
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true

1.5 Iniciar la Aplicación​

mvn clean install -DskipTests spring-boot:run

1.6 Consola H2​

URL: http://localhost:8080/h2-console/

Conexión:

  • JDBC URL: jdbc:h2:mem:testdb
  • Username: sa
  • Password: (vacío)

1.7 Probar el CRUD​

CREATE - Insertar:

INSERT INTO TBL_EMPLOYEES (FIRST_NAME, LAST_NAME, EMAIL) 
VALUES ('Jean', 'Tremblay', 'jean@example.com');

INSERT INTO TBL_EMPLOYEES (FIRST_NAME, LAST_NAME, EMAIL)
VALUES ('Marie', 'Gagnon', 'marie@example.com');

READ - Consultar:

SELECT * FROM TBL_EMPLOYEES;

UPDATE - Modificar:

UPDATE TBL_EMPLOYEES 
SET EMAIL = 'nouveau@example.com'
WHERE FIRST_NAME = 'Jean';

DELETE - Eliminar:

DELETE FROM TBL_EMPLOYEES WHERE ID = 1;

1.8 Prueba de Persistencia​

Prueba 1: Desconexión/Re-conexión

  • Desconéctese de H2
  • NO detenga la aplicación
  • Vuelva a conectarse
  • Resultado: ✅ Los datos siguen ahí

Prueba 2: Parar/Reiniciar

  • Detenga la aplicación (Ctrl + C)
  • Reinicie: mvn clean install -DskipTests spring-boot:run
  • Vuelva a conectarse
  • Resultado: ❌ Tabla vacía (datos perdidos)

¿Por qué? Modo memoria + ddl-auto=create-drop


Parte 2: H2 Persistente (Datos en Disco)​

2.1 Nuevo Proyecto​

Opción 1: Duplicar el proyecto h2-memoire y renombrar a h2-persistance

Opción 2: Crear nuevo proyecto desde Spring Initializr


2.2 Copiar Entidad y Repository​

Copie los mismos archivos Employee.java y EmployeeRepository.java de la Parte 1.


2.3 Configuración Modificada​

Archivo: src/main/resources/application.properties

# Console H2
spring.h2.console.enabled=true

# Base de datos en DISCO (diferencia clave)
spring.datasource.url=jdbc:h2:file:C:/temp/test;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# Hibernate
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Cambios clave:

  • jdbc:h2:mem: → jdbc:h2:file:C:/temp/test
  • ddl-auto=create-drop → ddl-auto=update

2.4 Iniciar la Aplicación​

mvn clean install -DskipTests spring-boot:run

2.5 Consola H2​

URL: http://localhost:8080/h2-console/

Conexión:

  • JDBC URL: jdbc:h2:file:C:/temp/test
  • Username: sa
  • Password: (vacío)

2.6 Probar el CRUD​

INSERT INTO TBL_EMPLOYEES (FIRST_NAME, LAST_NAME, EMAIL) 
VALUES ('Pierre', 'Roy', 'pierre@example.com');

SELECT * FROM TBL_EMPLOYEES;

2.7 Prueba de Persistencia​

Prueba: Parar/Reiniciar

  1. Inserte datos
  2. Detenga la aplicación (Ctrl + C)
  3. Reinicie: mvn clean install -DskipTests spring-boot:run
  4. Vuelva a conectarse
  5. Resultado: ✅ ¡Datos siguen ahí!

Verificación del archivo:

  • Ir a C:\temp\
  • Archivo test.mv.db creado (su base de datos)

Comparación: Memoria vs Archivo​

AspectoModo MemoriaModo Archivo
URLjdbc:h2:mem:testdbjdbc:h2:file:C:/temp/test
ddl-autocreate-dropupdate
Persistencia❌ No✅ Sí
Archivo .mv.dbNo creadoCreado en disco
UsoPruebas, desarrolloDesarrollo con datos

Resumen​

Puntos Clave​

  • Entidad JPA con @Entity y @Table - Hibernate crea la tabla automáticamente
  • Repository con JpaRepository - 4 métodos CRUD incluidos
  • H2 memoria - Rápido pero temporal
  • H2 archivo - Persistencia de datos en disco
  • Consola H2 - Interfaz para probar el CRUD

4 Métodos CRUD Básicos​

MétodoAcción
save(entity)CREATE / UPDATE
findById(id)READ uno
findAll()READ todos
deleteById(id)DELETE

Ejercicio​

Cree una nueva entidad Product:

  • id, name, price, quantity
  • ProductRepository
  • Pruebe en modo memoria
  • Pruebe en modo archivo

Volver al Módulo 2