EntityHelper.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.generator.model.interfaces.WithId;
  9. import java.util.Objects;

  10. /**
  11.  * Helper to normalize common operations on WithId objects
  12.  *
  13.  * @author maxence
  14.  */
  15. public class EntityHelper {

  16.     /**
  17.      * never-called private constructor
  18.      */
  19.     private EntityHelper() {
  20.         throw new UnsupportedOperationException(
  21.             "This is a utility class and cannot be instantiated");
  22.     }

  23.     /**
  24.      * {@link Object#hashCode} implementation for all WithId implementation
  25.      *
  26.      * @param object object to hash
  27.      *
  28.      * @return a hash code value for the given object.
  29.      */
  30.     public static int hashCode(WithId object) {
  31.         int hash = 7;
  32.         hash = 31 * hash + Objects.hashCode(object.getId());
  33.         return hash;
  34.     }

  35.     /**
  36.      * {@link Object#equals} implementation for all WithId implementation. Objects equal if
  37.      * <ul>
  38.      * <li>it's the same reference (strict == equality)
  39.      * <li>both are null
  40.      * <li>they are instance of the same class and have the same id
  41.      * </ul>
  42.      *
  43.      * @param a first object
  44.      * @param b second object
  45.      *
  46.      * @return {@code true} if both objects represent the same persisted entity
  47.      */
  48.     public static boolean equals(WithId a, Object b) {
  49.         if (a == b) {
  50.             // same object or both are null
  51.             return true;
  52.         }
  53.         if (a == null || b == null) {
  54.             // only one is null
  55.             return false;
  56.         }

  57.         // at this point, both are not null
  58.         if (a.getClass() != b.getClass()) {
  59.             // class mismatch
  60.             return false;
  61.         } else {
  62.             // same class
  63.             WithId otherB = (WithId) b;
  64.             if (a.getId() == null || otherB.getId() == null) {
  65.                 // if at least one object has no id, object are not equals
  66.                 // if both id are null, objects may equal, but this case is handled by the strict
  67.                 // (a == b) equality check
  68.                 return false;
  69.             }
  70.             // same class, ids must equals
  71.             return Objects.equals(a.getId(), otherB.getId());
  72.         }
  73.     }
  74. }