Class CsvRepositoryHelper<ID,T>

java.lang.Object
com.ntu.fdae.group1.bto.repository.util.CsvRepositoryHelper<ID,T>
Type Parameters:
ID - The type of identifier used for entities
T - The entity type this helper manages

public class CsvRepositoryHelper<ID,T> extends Object
Helper class that provides common CSV file operations for repositories.

This class encapsulates the logic for reading from and writing to CSV files, providing a reusable component for repository implementations. It handles serialization and deserialization between entity objects and CSV format.

  • Constructor Details

    • CsvRepositoryHelper

      public CsvRepositoryHelper(String filePath, String[] csvHeader, Function<List<String[]>,Map<ID,T>> deserializer, Function<Map<ID,T>,List<String[]>> serializer)
      Constructs a new CsvRepositoryHelper with the specified parameters.
      Parameters:
      filePath - The path to the CSV file
      csvHeader - The header row for the CSV file
      deserializer - Function that takes List<String[]> read from CSV and returns Map<ID, T>
      serializer - Function that takes the current Map<ID, T> and returns List<String[]> to be written
  • Method Details

    • loadData

      public Map<ID,T> loadData() throws DataAccessException
      Loads data from the CSV file and converts it to a map of entities.

      This method reads the CSV file at the configured path, skips the header row, and uses the provided deserializer function to convert the CSV data into entity objects.

      Returns:
      A map of entities, keyed by their identifiers
      Throws:
      DataAccessException - If an error occurs while reading or parsing the CSV file
    • saveData

      public void saveData(Map<ID,T> entities) throws DataAccessException
      Saves a map of entities to the CSV file.

      This method uses the provided serializer function to convert entity objects into CSV data, then writes that data to the configured file path with the specified header.

      Parameters:
      entities - The map of entities to save
      Throws:
      DataAccessException - If an error occurs while writing to the CSV file