Skip to main content

Overview

The DB_EnterpriseH2 class is a complete enterprise database management system using H2 Database Engine. It provides the same functionality as DB_EnterpriseHSQLDB but optimized for H2, including automatic database file cleanup and file-based storage.

Class Information

Class
public class
DB_EnterpriseH2JDBC Driver: org.h2.Driver

Database Constants

URL
String
H2 database connection URL with auto-server mode and persistent connection
private static final String URL = "jdbc:h2:file:./db_empresa_h2;AUTO_SERVER=TRUE;DB_CLOSE_DELAY=-1";
AUTO_SERVER
boolean
default:"TRUE"
Enables multiple concurrent connections to the same database
DB_CLOSE_DELAY
int
default:"-1"
Keeps database open until JVM shutdown (-1 = never auto-close)
USER
String
default:"SA"
Database username constant
private static final String USER = "SA";
PASSWORD
String
default:""
Database password (empty by default)
private static final String PASSWORD = "";

Main Method

Signature

public static void main(String[] args)

Workflow

Class.forName("org.h2.Driver");

Core Methods

eliminarArchivosBD()

private static void eliminarArchivosBD()
Purpose
Deletes existing H2 database files before creating a fresh database
Files Removed
  • db_empresa_h2.mv.db - Main database file
  • db_empresa_h2.trace.db - Trace/log file
File dbFile1 = new File("db_empresa_h2.mv.db");
File dbFile2 = new File("db_empresa_h2.trace.db");

if (dbFile1.exists()) {
    if (dbFile1.delete()) {
        System.out.println("Archivo de BD anterior eliminado: " + dbFile1.getName());
    } else {
        System.out.println("No se pudo eliminar el archivo: " + dbFile1.getName());
    }
}

if (dbFile2.exists()) {
    if (dbFile2.delete()) {
        System.out.println("Archivo de trazas eliminado: " + dbFile2.getName());
    }
}

inicializarBaseDatos()

private static void inicializarBaseDatos()
Purpose
Checks if tables exist and creates the complete schema if needed
DatabaseMetaData meta = conn.getMetaData();
ResultSet tables = meta.getTables(null, null, "T_EMPLEADOS", null);

if (!tables.next()) {
    crearEsquemaCompleto(conn);
    System.out.println("Creando base de datos H2...");
} else {
    System.out.println("Base de datos H2 ya existe.");
}

crearEsquemaCompleto()

private static void crearEsquemaCompleto(Connection conn) throws SQLException
conn
Connection
required
Active H2 database connection
Tables Created
  • t_centros - Work centers/locations
  • t_departamentos - Departments with foreign key to centers
  • t_empleados - Employees with foreign key to departments
CREATE TABLE t_centros (
    codigo_centro INTEGER PRIMARY KEY,
    nombre_centro VARCHAR(21) NOT NULL,
    ubicacion VARCHAR(50) NOT NULL
)
private static void menuPrincipal()
Menu Options
  1. Ver empleados
  2. Agregar empleado
  3. Buscar empleados
  4. Ver departamentos
  5. Eliminar empleado
  6. Información completa con JOINs
  7. Salir

CRUD Operations

verEmpleados()

private static void verEmpleados()
String sql = "SELECT e.*, d.nombre_departamento FROM t_empleados e " +
            "JOIN t_departamentos d ON e.codigo_departamento = d.codigo_departamento";
Displays employee information with department names using JOIN

agregarEmpleado()

private static void agregarEmpleado()
User Input
Interactive
  • Código (Employee ID)
  • Departamento (Department ID)
  • Nombre (Employee Name)
  • Salario (Base Salary)
  • Fecha ingreso (Hire Date in YYYY-MM-DD format)
String sql = "INSERT INTO t_empleados (codigo_empleado, codigo_departamento, " +
            "extension_telefonica_empleado, fecha_nacimiento_empleado, " +
            "fecha_ingreso_empleado, salario_base_empleado, comision_empleado, " +
            "numero_hijos_empleado, nombre_empleado) VALUES (?, ?, 100, '1990-01-01', ?, ?, 0, 0, ?)";

pstmt.setInt(1, codigo);        // Employee code
pstmt.setInt(2, depto);         // Department code
pstmt.setString(3, fecha);      // Hire date
pstmt.setDouble(4, salario);    // Salary
pstmt.setString(5, nombre);     // Name
pstmt.executeUpdate();

buscarEmpleados()

private static void buscarEmpleados()
nombre
String
Partial name for LIKE search
String sql = "SELECT * FROM t_empleados WHERE nombre_empleado LIKE ?";
pstmt.setString(1, "%" + nombre + "%");
ResultSet rs = pstmt.executeQuery();

verDepartamentos()

private static void verDepartamentos()
Output
Lists all departments with ID, name, and budget information
String sql = "SELECT * FROM t_departamentos";

eliminarEmpleado()

private static void eliminarEmpleado()
codigo
int
required
Employee code to delete from the database
String sql = "DELETE FROM t_empleados WHERE codigo_empleado = ?";
ps.setInt(1, codigo);
int filasAfectadas = ps.executeUpdate();

if (filasAfectadas > 0) {
    System.out.println("Empleado eliminado correctamente");
} else {
    System.out.println("No se encontró el empleado con ese código");
}

informacionCompletaJoins()

private static void informacionCompletaJoins()
Purpose
Displays comprehensive employee information by joining three tables
String sql = "SELECT " +
            "e.codigo_empleado, " +
            "e.nombre_empleado, " +
            "e.salario_base_empleado, " +
            "e.fecha_ingreso_empleado, " +
            "d.nombre_departamento, " +
            "d.presupuesto_departamento, " +
            "c.nombre_centro, " +
            "c.ubicacion " +
            "FROM t_empleados e " +
            "JOIN t_departamentos d ON e.codigo_departamento = d.codigo_departamento " +
            "JOIN t_centros c ON d.codigo_centro = c.codigo_centro " +
            "ORDER BY e.codigo_empleado";
Joins
  • Employee → Department (via codigo_departamento)
  • Department → Center (via codigo_centro)

Sample Data

The database is populated with initial data during creation:
INSERT INTO t_centros VALUES (10, 'SEDE CENTRAL', 'C/ ALCALA, 820, MADRID');
INSERT INTO t_centros VALUES (20, 'RELACION CON CLIENTES', 'C/ ATOCHA, 405, MADRID');
Eight departments including:
  • 100: DIRECCION GENERAL (Budget: 120,000)
  • 110: DIRECCION COMERCIAL (Budget: 15,000)
  • 111: SECTOR INDUSTRIAL (Budget: 11,000)
  • 112: SECTOR SERVICIOS (Budget: 9,000)
  • 120: ORGANIZACION (Budget: 3,000)
  • 121: PERSONAL (Budget: 2,000)
  • 122: PROCESO DE DATOS (Budget: 6,000)
  • 130: FINANZAS (Budget: 2,000)
Six employees with complete information:
  • 110: PONS, CESAR (Salary: 3,100, Dept: 121 PERSONAL)
  • 120: LASA, MARIO (Salary: 3,500, Dept: 112 SECTOR SERVICIOS)
  • 130: TEROL, LUCIANO (Salary: 2,900, Dept: 112 SECTOR SERVICIOS)
  • 150: PEREZ, JULIO (Salary: 4,400, Dept: 121 PERSONAL)
  • 160: AGUIRRE, AUREO (Salary: 3,100, Dept: 111 SECTOR INDUSTRIAL)
  • 180: PEREZ, MARCOS (Salary: 4,800, Dept: 110 DIRECCION COMERCIAL)

H2-Specific Features

File Storage
File
Database stored in db_empresa_h2.mv.db file
AUTO_SERVER
boolean
default:"TRUE"
Allows multiple JVMs to connect to the same database file simultaneously
DB_CLOSE_DELAY
int
default:"-1"
Prevents automatic database closure when last connection closes

Error Handling

catch (SQLException e) {
    System.out.println("Error: " + e.getMessage());
}

Differences from HSQLDB Version

FeatureDB_EnterpriseH2DB_EnterpriseHSQLDB
Driverorg.h2.Driverorg.hsqldb.jdbc.JDBCDriver
URL Formatjdbc:h2:filejdbc:hsqldb:file
Auto ServerAUTO_SERVER=TRUEN/A
File CleanupeliminarArchivosBD()No cleanup
Config FileHardcoded URLconfig.ini
Table CheckT_EMPLEADOST_CENTROS

Build docs developers (and LLMs) love