JpaCustomizer.java

  1. /*
  2.  * The coLAB project
  3.  * Copyright (C) 2021-2023 AlbaSim, MEI, HEIG-VD, HES-SO
  4.  *
  5.  * Licensed under the MIT License
  6.  */
  7. package ch.colabproject.colab.api.model.tools;

  8. import ch.colabproject.colab.api.Helper;
  9. import org.eclipse.persistence.config.SessionCustomizer;
  10. import org.eclipse.persistence.descriptors.ClassDescriptor;
  11. import org.eclipse.persistence.mappings.DirectToFieldMapping;
  12. import org.eclipse.persistence.sessions.Session;

  13. /**
  14.  * Customize JPA session.
  15.  * <ul>
  16.  * <li>use lowercase with underscore database field names
  17.  * </ul>
  18.  *
  19.  * @author maxence
  20.  */
  21. public class JpaCustomizer implements SessionCustomizer {

  22.     @Override
  23.     public void customize(Session session) throws Exception {
  24.         session.getDescriptors().values().forEach(this::updateFieldNameMapping);
  25.     }

  26.     /**
  27.      * custom field names
  28.      *
  29.      * @param desc mappings to override
  30.      */
  31.     private void updateFieldNameMapping(ClassDescriptor desc) {
  32.         desc.getMappings().stream()
  33.             .filter(mapping -> (mapping.isDirectToFieldMapping()))
  34.             .map(mapping -> (DirectToFieldMapping) mapping)
  35.             .forEachOrdered(directMapping -> {
  36.                 // format: table_name.FIELD ->[ tableNane, fieldName];
  37.                 String[] names = directMapping.getFieldName().split("\\.");
  38.                 if (names.length == 2) {
  39.                     String newName = Helper.camelCaseToUnderscore(directMapping.getAttributeName());
  40.                     directMapping.getField().setName(newName);
  41.                 }
  42.             }
  43.             );
  44.     }
  45. }