Skip to main content

Overview

EduTec Backend uses Spring Data JPA with Hibernate as the ORM (Object-Relational Mapping) provider. The application supports multiple database systems, with MySQL 8.0.19 as the primary production database.
The flexible database architecture allows development with H2 (in-memory) while deploying to MySQL, Oracle, MariaDB, or SQL Server in production without code changes.

Supported Databases

The project includes JDBC drivers for multiple database systems:
Version: 8.0.19Status: Primary production database
Connection URL Pattern:
MySQL 8.0+ requires the cj package in the driver class name. The older com.mysql.jdbc.Driver is deprecated.

JPA Configuration

The application uses Spring Data JPA for database operations:
This starter includes:
  • Spring Data JPA - Repository abstraction layer
  • Hibernate Core - JPA implementation
  • Spring Transaction Management - Declarative transaction support
  • JDBC Connection Pooling - HikariCP (default in Spring Boot 2.x)

Entity Model: User

The User entity represents the core authentication and user management table.

Entity Definition

Annotations Explained

Purpose: Marks this class as a JPA entity that maps to a database tableEffect: Hibernate will manage instances of this class and persist them to the database
Purpose: Specifies the database table nameDefault: Without this annotation, the table name would be user (class name in lowercase)Custom Name: Maps to the usuarios table in the database
Using a Spanish table name (usuarios) indicates this may be for a Spanish-speaking user base or legacy database naming conventions.
@Data - Generates:
  • Getters for all fields
  • Setters for all non-final fields
  • toString() method
  • equals() and hashCode() methods
  • Required arguments constructor
@NoArgsConstructor - Generates a no-argument constructor (required by JPA)@AllArgsConstructor - Generates a constructor with all fields as parameters
These Lombok annotations dramatically reduce boilerplate code. Without them, you would need to manually write ~50 lines of getters, setters, and other methods.
@Id - Marks this field as the primary key@GeneratedValue(strategy = GenerationType.IDENTITY):
  • Delegates primary key generation to the database
  • Uses AUTO_INCREMENT (MySQL/MariaDB) or IDENTITY columns (SQL Server)
  • Database generates the ID when inserting new records
Alternative Strategies:
  • AUTO - JPA provider chooses the strategy
  • SEQUENCE - Uses database sequences (Oracle, PostgreSQL)
  • TABLE - Uses a separate table to generate IDs
  • UUID - Generates UUIDs (requires custom generator)
Username Field:
  • nullable = false: NOT NULL constraint - username is required
  • unique = true: UNIQUE constraint - no duplicate usernames
Password Field:
  • nullable = false: Password is required
The password field stores plain text in the current implementation. Always hash passwords using BCrypt before storing them in production.

Generated Database Schema

Hibernate will generate the following SQL DDL:
Column Types:
  • id: BIGINT (maps from Java Long)
  • username: VARCHAR(255) (default String length)
  • password: VARCHAR(255)
Hibernate automatically creates an index on the username column due to the unique = true constraint, optimizing login queries.

Hibernate Configuration

The project includes several Hibernate extensions and utilities:

Hibernate Core Dependencies

Purpose: Connection pool integration
Agroal is a modern connection pool that provides:
  • Fast connection acquisition
  • Leak detection
  • Connection validation
  • Metrics and monitoring
Purpose: Full-text search capabilities using Apache Lucene
Use Cases:
  • Search users by name or email
  • Autocomplete functionality
  • Advanced text queries (fuzzy matching, wildcards)
Example Usage:
Purpose: Bean validation (JSR 380 implementation)
Example Validations:
Purpose: Entity auditing and versioning
Spring Data Integration:
Features:
  • Track all changes to entities
  • Query historical data
  • Audit trail compliance
  • Rollback capability
Enable Auditing:
Envers creates shadow audit tables (e.g., usuarios_AUD) that store historical versions of each entity, perfect for compliance requirements.

Database Configuration

Current configuration in application.properties:
Missing Database ConfigurationThe application.properties file only contains the application name. You must add database connection properties before running the application:

Configuration Properties Explained

Controls automatic schema management:
  • none - No automatic schema operations
  • validate - Validate schema matches entities (safe for production)
  • update - Update schema to match entities (adds columns/tables, never drops)
  • create - Drop and recreate schema on startup
  • create-drop - Create on startup, drop on shutdown
Use validate or none in production with proper database migration tools like Flyway or Liquibase.

Data Access Pattern

While not shown in the current codebase, typical Spring Data JPA usage would include:

Repository Interface

Spring Data JPA automatically implements:
  • save(User user) - Insert or update
  • findById(Long id) - Find by primary key
  • findAll() - Get all users
  • deleteById(Long id) - Delete by primary key
  • count() - Count total users
Custom query methods:
  • findByUsername(String username) - Find user by username
  • existsByUsername(String username) - Check if username exists
Spring Data JPA derives the SQL query from the method name. No implementation code needed!

Service Layer Example

Migration Strategy

Development Phase

For development, use Hibernate’s automatic schema generation:

Production Deployment

For production, use database migration tools:
Add to pom.xml:
Create migrations in src/main/resources/db/migration/:
Configure:
Never use spring.jpa.hibernate.ddl-auto=update or create in production. Always use proper migration tools for schema changes.

Best Practices

Entity Design

  1. Always use @Column(nullable = false) for required fields - Database constraints are the last line of defense
  2. Add indexes for frequently queried columns:
  3. Use appropriate field types:
    • Long for IDs (not Integer)
    • LocalDateTime for timestamps (not Date)
    • BigDecimal for currency (not double)
  4. Add timestamps for auditing:

Performance Optimization

  1. Enable second-level cache:
  2. Use batch inserts:
  3. Configure connection pool properly:
    • Match pool size to your workload
    • Monitor connection usage
    • Set appropriate timeouts

Next Steps

  • Authentication - Integrate user authentication with database validation
  • Architecture - Understand how the repository layer fits into the overall system
  • API Reference - Explore endpoints that interact with the database