Overview
This guide demonstrates how to set up and configure H2 Database as an alternative database engine for the enterprise management system. H2 is a fast, open-source, embedded SQL database written in Java that provides excellent compatibility and performance.Prerequisites
Ensure you have the following before starting:
- Java Development Kit (JDK) 8 or higher
- H2 Database JDBC driver (h2-*.jar)
- Basic understanding of JDBC and SQL
Database Connection Setup
private static final String URL = "jdbc:h2:file:./db_empresa_h2;AUTO_SERVER=TRUE;DB_CLOSE_DELAY=-1";
private static final String USER = "SA";
private static final String PASSWORD = "";
Key connection parameters:
file:./db_empresa_h2- Creates a file-based database in the current directoryAUTO_SERVER=TRUE- Allows multiple processes to access the databaseDB_CLOSE_DELAY=-1- Keeps the database open as long as the JVM is running
private static void inicializarBaseDatos() {
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
// Verify if tables already exist
DatabaseMetaData meta = conn.getMetaData();
ResultSet tables = meta.getTables(null, null, "T_EMPLEADOS", null);
if (!tables.next()) {
// Tables don't exist, create them
crearEsquemaCompleto(conn);
System.out.println("Creando base de datos H2...");
} else {
System.out.println("Base de datos H2 ya existe.");
}
} catch (SQLException e) {
System.out.println("Error al inicializar BD H2: " + e.getMessage());
}
}
private static void eliminarArchivosBD() {
try {
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());
}
}
} catch (Exception e) {
System.out.println("Advertencia: No se pudieron eliminar archivos de BD: " + e.getMessage());
}
}
Database Schema Creation
The complete schema includes three interrelated tables:Creating Tables
Populating Initial Data
Insert sample data for all three tables:CRUD Operations with H2
Querying Data
Inserting Data
Searching with Pattern Matching
Deleting Records
Complex Multi-table JOIN
Retrieve complete employee information across all three tables:Running the Application
H2 Database Files
H2 creates the following files:db_empresa_h2.mv.db- Main database file (MVStore format)db_empresa_h2.trace.db- Trace and debug log (optional)
The
.mv.db extension indicates H2 is using the MVStore storage engine, which is the default for H2 version 1.4+Advantages of H2 Database
- Performance: Generally faster than HSQLDB for most operations
- Multi-threaded: Better support for concurrent access with AUTO_SERVER
- Compatibility modes: Can emulate other databases (MySQL, PostgreSQL, etc.)
- Web console: Built-in browser-based database console
- Small footprint: Single JAR file, no external dependencies
- Active development: Regularly updated with new features
H2 vs HSQLDB Comparison
| Feature | H2 | HSQLDB |
|---|---|---|
| Performance | Generally faster | Good performance |
| File format | MVStore (.mv.db) | Script-based (.script) |
| Concurrent access | AUTO_SERVER mode | Single process |
| Web console | Built-in | Separate tool |
| Memory usage | Higher | Lower |
| Compatibility | Multiple DB modes | Standard SQL |
Accessing H2 Web Console
H2 includes a web-based database console. To use it:http://localhost:8082 with:
- JDBC URL:
jdbc:h2:file:./db_empresa_h2 - User:
SA - Password: (empty)
Next Steps
- Compare with HSQLDB Setup
- Learn to create a JAR deployment
- Explore advanced JDBC features