Esempio n. 1
0
  /**
   * Cascades the persist operation.
   *
   * @param entityManager the entity manager
   * @param processed registry of processed entities
   * @param instances the managed instances
   * @return true if an implicit flush is required, false otherwise
   * @since 2.0.0
   */
  public boolean cascadePersist(
      EntityManagerImpl entityManager,
      ArrayList<Object> processed,
      LinkedList<ManagedInstance<?>> instances) {
    ManagedInstance.LOG.debug("Cascading persist on {0}", this);

    boolean requiresFlush = false;

    for (final AssociationMappingImpl<?, ?, ?> association :
        this.type.getAssociationsPersistable()) {

      // if the association a collection attribute then we will cascade to each element
      if (association instanceof PluralAssociationMappingImpl) {
        final PluralAssociationMappingImpl<?, ?, ?> mapping =
            (PluralAssociationMappingImpl<?, ?, ?>) association;

        switch (mapping.getAttribute().getCollectionType()) {
          case MAP:
            // extract the map
            final Map<?, ?> map = (Map<?, ?>) mapping.get(this.instance);

            // cascade to each element in the map
            for (final Object element : map.values()) {
              requiresFlush |= entityManager.persistImpl(element, processed, instances);
            }

            break;
          case LIST:
            // extract the list
            final List<?> list = (List<?>) mapping.get(this.instance);

            // cascade to each element in the list
            for (int i = 0; i < list.size(); i++) {
              requiresFlush |= entityManager.persistImpl(list.get(i), processed, instances);
            }

            break;
          default:
            // extract the collection
            final Collection<?> collection = (Collection<?>) mapping.get(this.instance);

            // cascade to each element in the collection
            if (collection instanceof List) {
              final List<?> castedList = (List<?>) collection;
              for (int i = 0; i < castedList.size(); i++) {
                requiresFlush |= entityManager.persistImpl(castedList.get(i), processed, instances);
              }
            } else {
              for (final Object element : collection) {
                requiresFlush |= entityManager.persistImpl(element, processed, instances);
              }
            }

            break;
        }
      } else {
        final SingularAssociationMappingImpl<?, ?> mapping =
            (SingularAssociationMappingImpl<?, ?>) association;
        final Object associate = mapping.get(this.instance);
        if (associate != null) {
          requiresFlush |= entityManager.persistImpl(associate, processed, instances);
        }
      }
    }

    return requiresFlush;
  }