M Mateo Calvo

Preventing Duplicate Submissions in a Gym Management System

The Problem

In the gestion-nexo-gimnasio project, a gym management system, we encountered an issue where users could potentially submit duplicate attendance records due to concurrency. This could lead to inaccurate data and reporting.

The Approach

To address this, we implemented a multi-pronged approach focusing on database constraints and exception handling.

Phase 1: Unique Index Constraint

We added a unique index to the database table to prevent duplicate entries based on the user's identifier and the date. This ensures that only one attendance record can be created per user per day.

Here's an example of how the unique index was created using SQL:

CREATE UNIQUE INDEX unique_attendance ON attendance (user_id, attendance_date);

This SQL statement creates a unique index named unique_attendance on the attendance table, using the user_id and attendance_date columns. Any attempt to insert a row with the same user_id and attendance_date as an existing row will result in a database error.

Phase 2: Data Integrity Handling

We implemented exception handling in the SocioService to catch DataIntegrityViolationException, which occurs when the unique index constraint is violated. This exception is then translated into a custom AsistenciaDiariaException to provide a more specific error message to the user.

Here's an example of the Java code used to handle the exception:

try {
    // Attempt to save the attendance record
    attendanceRepository.save(attendance);
} catch (DataIntegrityViolationException e) {
    // Throw a custom exception
    throw new AsistenciaDiariaException("Daily attendance already recorded for this user.");
}

This Java code snippet demonstrates how a DataIntegrityViolationException is caught during the attendance record saving process. A custom AsistenciaDiariaException is then thrown to provide a more user-friendly error message.

Phase 3: Data Migration and Cleanup

As part of the solution, existing duplicate records were identified and removed during a data migration process. The most recent record was preserved to ensure data integrity.

Key Insight

By implementing a unique index constraint and handling potential exceptions, we effectively prevented duplicate attendance records, ensuring data accuracy and reliability in the gym management system. The combination of database-level constraints and application-level exception handling provides a robust solution to prevent concurrency issues.


Generated with Gitvlg.com

Preventing Duplicate Submissions in a Gym Management System
Mateo Calvo

Mateo Calvo

Author

Share: