public String addFromCollection(QueryTranslatorImpl q) throws QueryException {
    Type collectionElementType = getPropertyType();

    if (collectionElementType == null) {
      throw new QueryException(
          "must specify 'elements' for collection valued property in from clause: " + path);
    }

    if (collectionElementType.isEntityType()) {
      // an association
      QueryableCollection collectionPersister = q.getCollectionPersister(collectionRole);
      Queryable entityPersister = (Queryable) collectionPersister.getElementPersister();
      String clazz = entityPersister.getEntityName();

      final String elementName;
      if (collectionPersister.isOneToMany()) {
        elementName = collectionName;
        // allow index() function:
        q.decoratePropertyMapping(elementName, collectionPersister);
      } else { // many-to-many
        q.addCollection(collectionName, collectionRole);
        elementName = q.createNameFor(clazz);
        addJoin(elementName, (AssociationType) collectionElementType);
      }
      q.addFrom(elementName, clazz, joinSequence);
      currentPropertyMapping = new CollectionPropertyMapping(collectionPersister);
      return elementName;
    } else {
      // collections of values
      q.addFromCollection(collectionName, collectionRole, joinSequence);
      return collectionName;
    }
  }
Ejemplo n.º 2
0
  @Override
  @SuppressWarnings("unchecked")
  public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula)
      throws HibernateException {
    final Type elementType = persister.getElementType();
    final java.util.Map sn = (java.util.Map) getSnapshot();
    final ArrayList deletes = new ArrayList(sn.size());

    Iterator itr = sn.keySet().iterator();
    while (itr.hasNext()) {
      final Object test = itr.next();
      if (!set.contains(test)) {
        // the element has been removed from the set
        deletes.add(test);
      }
    }

    itr = set.iterator();
    while (itr.hasNext()) {
      final Object test = itr.next();
      final Object oldValue = sn.get(test);
      if (oldValue != null && elementType.isDirty(test, oldValue, getSession())) {
        // the element has changed
        deletes.add(oldValue);
      }
    }

    return deletes.iterator();
  }
Ejemplo n.º 3
0
  private Queryable determineAppropriateOwnerPersister(NonScalarReturn ownerDescriptor) {
    String entityName = null;
    if (ownerDescriptor instanceof RootReturn) {
      entityName = ((RootReturn) ownerDescriptor).getEntityName();
    } else if (ownerDescriptor instanceof CollectionReturn) {
      CollectionReturn collRtn = (CollectionReturn) ownerDescriptor;
      String role = collRtn.getOwnerEntityName() + "." + collRtn.getOwnerProperty();
      CollectionPersister persister = getFactory().getCollectionPersister(role);
      EntityType ownerType = (EntityType) persister.getElementType();
      entityName = ownerType.getAssociatedEntityName(getFactory());
    } else if (ownerDescriptor instanceof FetchReturn) {
      FetchReturn fetchRtn = (FetchReturn) ownerDescriptor;
      Queryable persister = determineAppropriateOwnerPersister(fetchRtn.getOwner());
      Type ownerType = persister.getPropertyType(fetchRtn.getOwnerProperty());
      if (ownerType.isEntityType()) {
        entityName = ((EntityType) ownerType).getAssociatedEntityName(getFactory());
      } else if (ownerType.isCollectionType()) {
        Type ownerCollectionElementType = ((CollectionType) ownerType).getElementType(getFactory());
        if (ownerCollectionElementType.isEntityType()) {
          entityName =
              ((EntityType) ownerCollectionElementType).getAssociatedEntityName(getFactory());
        }
      }
    }

    if (entityName == null) {
      throw new HibernateException("Could not determine fetch owner : " + ownerDescriptor);
    }

    return (Queryable) getFactory().getEntityPersister(entityName);
  }
  @Deprecated
  public static StandardProperty buildStandardProperty(Property property, boolean lazyAvailable) {
    final Type type = property.getValue().getType();

    // we need to dirty check collections, since they can cause an owner
    // version number increment

    // we need to dirty check many-to-ones with not-found="ignore" in order
    // to update the cache (not the database), since in this case a null
    // entity reference can lose information

    boolean alwaysDirtyCheck =
        type.isAssociationType() && ((AssociationType) type).isAlwaysDirtyChecked();

    return new StandardProperty(
        property.getName(),
        type,
        lazyAvailable && property.isLazy(),
        property.isInsertable(),
        property.isUpdateable(),
        property.getValueGenerationStrategy(),
        property.isOptional(),
        alwaysDirtyCheck || property.isUpdateable(),
        property.isOptimisticLocked(),
        property.getCascadeStyle(),
        property.getValue().getFetchMode());
  }
  // TODO we could cache such knowledge in a service if that turns out to be costly
  private String buildCollectionRole(OgmCollectionPersister collectionPersister) {
    String otherSidePropertyName = null;
    Loadable elementPersister = (Loadable) collectionPersister.getElementPersister();
    Type[] propertyTypes = elementPersister.getPropertyTypes();

    for (int index = 0; index < propertyTypes.length; index++) {
      Type type = propertyTypes[index];
      // we try and restrict type search as much as possible
      if (type.isAssociationType()) {
        boolean matching = false;
        // if the main side collection is a one-to-many, the reverse side should be a to-one is not
        // a collection
        if (collectionPersister.isOneToMany() && !type.isCollectionType()) {
          matching = isToOneMatching(elementPersister, index, type);
        }
        // if the main side collection is not a one-to-many, the reverse side should be a collection
        else if (!collectionPersister.isOneToMany() && type.isCollectionType()) {
          matching =
              isCollectionMatching((CollectionType) type, collectionPersister.getTableName());
        }
        if (matching) {
          otherSidePropertyName = elementPersister.getPropertyNames()[index];
          break;
        }
      }
    }
    return processOtherSidePropertyName(otherSidePropertyName);
  }
        public void noCascade(
            EventSource session,
            Object child,
            Object parent,
            EntityPersister persister,
            int propertyIndex) {
          if (child == null) {
            return;
          }
          Type type = persister.getPropertyTypes()[propertyIndex];
          if (type.isEntityType()) {
            String childEntityName =
                ((EntityType) type).getAssociatedEntityName(session.getFactory());

            if (!isInManagedState(child, session)
                && !(child
                    instanceof
                    HibernateProxy) // a proxy cannot be transient and it breaks
                                    // ForeignKeys.isTransient
                && ForeignKeys.isTransient(childEntityName, child, null, session)) {
              String parentEntiytName = persister.getEntityName();
              String propertyName = persister.getPropertyNames()[propertyIndex];
              throw new TransientObjectException(
                  "object references an unsaved transient instance - "
                      + "save the transient instance before flushing: "
                      + parentEntiytName
                      + "."
                      + propertyName
                      + " -> "
                      + childEntityName);
            }
          }
        }
Ejemplo n.º 7
0
 /**
  * Walk the association tree for an entity, adding associations which should be join fetched to
  * the {@link #associations} inst var. This form is the entry point into the walking for a given
  * entity, starting the recursive calls into {@link
  * #walkEntityTree(org.hibernate.persister.entity.OuterJoinLoadable, String, PropertyPath ,int)}.
  *
  * @param persister The persister representing the entity to be walked.
  * @param alias The (root) alias to use for this entity/persister.
  * @param path The property path to the entity being walked
  * @param currentDepth The current join depth
  * @throws org.hibernate.MappingException ???
  */
 private void walkEntityTree(
     final OuterJoinLoadable persister,
     final String alias,
     final PropertyPath path,
     final int currentDepth)
     throws MappingException {
   int n = persister.countSubclassProperties();
   for (int i = 0; i < n; i++) {
     Type type = persister.getSubclassPropertyType(i);
     if (type.isAssociationType()) {
       walkEntityAssociationTree(
           (AssociationType) type,
           persister,
           i,
           alias,
           path,
           persister.isSubclassPropertyNullable(i),
           currentDepth);
     } else if (type.isComponentType()) {
       walkComponentTree(
           (CompositeType) type,
           i,
           0,
           persister,
           alias,
           path.append(persister.getSubclassPropertyName(i)),
           currentDepth);
     }
   }
 }
 private FromElement createCollectionJoin(JoinSequence collectionJoinSequence, String tableAlias)
     throws SemanticException {
   String text = queryableCollection.getTableName();
   AST ast = createFromElement(text);
   FromElement destination = (FromElement) ast;
   Type elementType = queryableCollection.getElementType();
   if (elementType.isCollectionType()) {
     throw new SemanticException("Collections of collections are not supported!");
   }
   destination.initializeCollection(fromClause, classAlias, tableAlias);
   destination.setType(JOIN_FRAGMENT); // Tag this node as a JOIN.
   destination.setIncludeSubclasses(false); // Don't include subclasses in the join.
   destination.setCollectionJoin(true); // This is a clollection join.
   destination.setJoinSequence(collectionJoinSequence);
   destination.setOrigin(origin, false);
   destination.setCollectionTableAlias(tableAlias);
   //		origin.addDestination( destination );
   // This was the cause of HHH-242
   //		origin.setType( FROM_FRAGMENT );			// Set the parent node type so that the AST is properly
   // formed.
   origin.setText(""); // The destination node will have all the FROM text.
   origin.setCollectionJoin(
       true); // The parent node is a collection join too (voodoo - see JoinProcessor)
   fromClause.addCollectionJoinFromElementByPath(path, destination);
   fromClause.getWalker().addQuerySpaces(queryableCollection.getCollectionSpaces());
   return destination;
 }
  FromElement createCollection(
      QueryableCollection queryableCollection,
      String role,
      int joinType,
      boolean fetchFlag,
      boolean indexed)
      throws SemanticException {
    if (!collection) {
      throw new IllegalStateException("FromElementFactory not initialized for collections!");
    }
    this.inElementsFunction = indexed;
    FromElement elem;
    this.queryableCollection = queryableCollection;
    collectionType = queryableCollection.getCollectionType();
    String roleAlias = fromClause.getAliasGenerator().createName(role);

    // Correlated subqueries create 'special' implied from nodes
    // because correlated subselects can't use an ANSI-style join
    boolean explicitSubqueryFromElement = fromClause.isSubQuery() && !implied;
    if (explicitSubqueryFromElement) {
      String pathRoot = StringHelper.root(path);
      FromElement origin = fromClause.getFromElement(pathRoot);
      if (origin == null || origin.getFromClause() != fromClause) {
        implied = true;
      }
    }

    // super-duper-classic-parser-regression-testing-mojo-magic...
    if (explicitSubqueryFromElement && DotNode.useThetaStyleImplicitJoins) {
      implied = true;
    }

    Type elementType = queryableCollection.getElementType();
    if (elementType.isEntityType()) { // A collection of entities...
      elem = createEntityAssociation(role, roleAlias, joinType);
    } else if (elementType.isComponentType()) { // A collection of components...
      JoinSequence joinSequence = createJoinSequence(roleAlias, joinType);
      elem = createCollectionJoin(joinSequence, roleAlias);
    } else { // A collection of scalar elements...
      JoinSequence joinSequence = createJoinSequence(roleAlias, joinType);
      elem = createCollectionJoin(joinSequence, roleAlias);
    }

    elem.setRole(role);
    elem.setQueryableCollection(queryableCollection);
    // Don't include sub-classes for implied collection joins or subquery joins.
    if (implied) {
      elem.setIncludeSubclasses(false);
    }

    if (explicitSubqueryFromElement) {
      elem.setInProjectionList(true); // Treat explict from elements in sub-queries properly.
    }

    if (fetchFlag) {
      elem.setFetch(true);
    }
    return elem;
  }
  FromElement createElementJoin(QueryableCollection queryableCollection) throws SemanticException {
    FromElement elem;

    implied =
        true; // TODO: always true for now, but not if we later decide to support elements() in the
              // from clause
    inElementsFunction = true;
    Type elementType = queryableCollection.getElementType();
    if (!elementType.isEntityType()) {
      throw new IllegalArgumentException(
          "Cannot create element join for a collection of non-entities!");
    }
    this.queryableCollection = queryableCollection;
    SessionFactoryHelper sfh = fromClause.getSessionFactoryHelper();
    FromElement destination = null;
    String tableAlias = null;
    EntityPersister entityPersister = queryableCollection.getElementPersister();
    tableAlias = fromClause.getAliasGenerator().createName(entityPersister.getEntityName());
    String associatedEntityName = entityPersister.getEntityName();
    EntityPersister targetEntityPersister = sfh.requireClassPersister(associatedEntityName);
    // Create the FROM element for the target (the elements of the collection).
    destination =
        createAndAddFromElement(
            associatedEntityName,
            classAlias,
            targetEntityPersister,
            (EntityType) queryableCollection.getElementType(),
            tableAlias);
    // If the join is implied, then don't include sub-classes on the element.
    if (implied) {
      destination.setIncludeSubclasses(false);
    }
    fromClause.addCollectionJoinFromElementByPath(path, destination);
    //		origin.addDestination(destination);
    // Add the query spaces.
    fromClause.getWalker().addQuerySpaces(entityPersister.getQuerySpaces());

    CollectionType type = queryableCollection.getCollectionType();
    String role = type.getRole();
    String roleAlias = origin.getTableAlias();

    String[] targetColumns = sfh.getCollectionElementColumns(role, roleAlias);
    AssociationType elementAssociationType = sfh.getElementAssociationType(type);

    // Create the join element under the from element.
    int joinType = JoinFragment.INNER_JOIN;
    JoinSequence joinSequence =
        sfh.createJoinSequence(
            implied, elementAssociationType, tableAlias, joinType, targetColumns);
    elem = initializeJoin(path, destination, joinSequence, targetColumns, origin, false);
    elem.setUseFromFragment(
        true); // The associated entity is implied, but it must be included in the FROM.
    elem.setCollectionTableAlias(roleAlias); // The collection alias is the role.
    return elem;
  }
 public boolean equalsSnapshot(CollectionPersister persister) throws HibernateException {
   Type elementType = persister.getElementType();
   Serializable snapshot = getSnapshot();
   int xlen = Array.getLength(snapshot);
   if (xlen != Array.getLength(array)) return false;
   for (int i = 0; i < xlen; i++) {
     if (elementType.isDirty(Array.get(snapshot, i), Array.get(array, i), getSession()))
       return false;
   }
   return true;
 }
Ejemplo n.º 12
0
 private boolean indicatesCollection(Type type) {
   if (type.isCollectionType()) {
     return true;
   } else if (type.isComponentType()) {
     Type[] subtypes = ((CompositeType) type).getSubtypes();
     for (int i = 0; i < subtypes.length; i++) {
       if (indicatesCollection(subtypes[i])) {
         return true;
       }
     }
   }
   return false;
 }
 private void initAssociationKeyMetadata() {
   for (int index = 0; index < getPropertySpan(); index++) {
     final Type uniqueKeyType = getPropertyTypes()[index];
     if (uniqueKeyType.isEntityType()) {
       String[] propertyColumnNames = getPropertyColumnNames(index);
       AssociationKeyMetadata metadata =
           new AssociationKeyMetadata(getTableName(), propertyColumnNames);
       metadata.setRowKeyColumnNames(
           buildRowKeyColumnNamesForStarToOne(this, propertyColumnNames));
       associationKeyMetadataPerPropertyName.put(getPropertyNames()[index], metadata);
     }
   }
 }
Ejemplo n.º 14
0
  /**
   * Construct a new key for a caching natural identifier resolutions into the second level cache.
   * Note that an entity name should always be the root entity name, not a subclass entity name.
   *
   * @param naturalIdValues The naturalIdValues associated with the cached data
   * @param persister The persister for the entity
   * @param session The originating session
   */
  public NaturalIdCacheKey(
      final Object[] naturalIdValues,
      final EntityPersister persister,
      final SessionImplementor session) {

    this.entityName = persister.getRootEntityName();
    this.tenantId = session.getTenantIdentifier();

    this.naturalIdValues = new Serializable[naturalIdValues.length];

    final SessionFactoryImplementor factory = session.getFactory();
    final int[] naturalIdPropertyIndexes = persister.getNaturalIdentifierProperties();
    final Type[] propertyTypes = persister.getPropertyTypes();

    final int prime = 31;
    int result = 1;
    result = prime * result + ((this.entityName == null) ? 0 : this.entityName.hashCode());
    result = prime * result + ((this.tenantId == null) ? 0 : this.tenantId.hashCode());
    for (int i = 0; i < naturalIdValues.length; i++) {
      final Type type = propertyTypes[naturalIdPropertyIndexes[i]];
      final Object value = naturalIdValues[i];

      result = prime * result + (value != null ? type.getHashCode(value, factory) : 0);

      this.naturalIdValues[i] = type.disassemble(value, session, null);
    }

    this.hashCode = result;
    this.toString =
        new ValueHolder<String>(
            new ValueHolder.DeferredInitializer<String>() {
              @Override
              public String initialize() {
                // Complex toString is needed as naturalIds for entities are not simply based on a
                // single value like primary keys
                // the only same way to differentiate the keys is to included the disassembled
                // values in the string.
                final StringBuilder toStringBuilder =
                    new StringBuilder(entityName).append("##NaturalId[");
                for (int i = 0; i < naturalIdValues.length; i++) {
                  toStringBuilder.append(naturalIdValues[i]);
                  if (i + 1 < naturalIdValues.length) {
                    toStringBuilder.append(", ");
                  }
                }
                toStringBuilder.append("]");

                return toStringBuilder.toString();
              }
            });
  }
Ejemplo n.º 15
0
 private void determineKeySelectExpressions(
     QueryableCollection collectionPersister, List selections) {
   AliasGenerator aliasGenerator = new LocalAliasGenerator(0);
   appendSelectExpressions(collectionPersister.getIndexColumnNames(), selections, aliasGenerator);
   Type keyType = collectionPersister.getIndexType();
   if (keyType.isAssociationType()) {
     EntityType entityType = (EntityType) keyType;
     Queryable keyEntityPersister =
         (Queryable) sfi().getEntityPersister(entityType.getAssociatedEntityName(sfi()));
     SelectFragment fragment =
         keyEntityPersister.propertySelectFragmentFragment(collectionTableAlias(), null, false);
     appendSelectExpressions(fragment, selections, aliasGenerator);
   }
 }
Ejemplo n.º 16
0
  /**
   * Walk the association tree for an entity, adding associations which should be join fetched to
   * the {@link #associations} inst var. This form is the entry point into the walking for a given
   * entity, starting the recursive calls into {@link
   * #walkEntityTree(org.hibernate.persister.entity.OuterJoinLoadable, String, PropertyPath ,int)}.
   *
   * @param persister The persister representing the entity to be walked.
   * @param alias The (root) alias to use for this entity/persister.
   * @param path The property path to the entity being walked
   * @param currentDepth The current join depth
   * @throws org.hibernate.MappingException ???
   */
  private void walkEntityTree(
      final OuterJoinLoadable persister,
      final String alias,
      final PropertyPath path,
      final int currentDepth)
      throws MappingException {
    int n = persister.countSubclassProperties();
    for (int i = 0; i < n; i++) {
      Type type = persister.getSubclassPropertyType(i);
      if (type.isAssociationType()) {
        walkEntityAssociationTree(
            (AssociationType) type,
            persister,
            i,
            alias,
            path,
            persister.isSubclassPropertyNullable(i),
            currentDepth);
      } else if (type.isComponentType()) {
        walkComponentTree(
            (CompositeType) type,
            i,
            0,
            persister,
            alias,
            path.append(persister.getSubclassPropertyName(i)),
            currentDepth);
      }
    }

    // if the entity has a composite identifier, see if we need to handle
    // its sub-properties separately
    final Type idType = persister.getIdentifierType();
    if (idType.isComponentType()) {
      final CompositeType cidType = (CompositeType) idType;
      if (cidType.isEmbedded()) {
        // we have an embedded composite identifier.  Most likely we need to process the composite
        // properties separately, although there is an edge case where the identifier is really
        // a simple identifier (single value) wrapped in a JPA @IdClass or even in the case of a
        // a simple identifier (single value) wrapped in a Hibernate composite type.
        //
        // We really do not have a built-in method to determine that.  However, generally the
        // persister would report that there is single, physical identifier property which is
        // explicitly at odds with the notion of "embedded composite".  So we use that for now
        if (persister.getEntityMetamodel().getIdentifierProperty().isEmbedded()) {
          walkComponentTree(cidType, -1, 0, persister, alias, path.append(""), currentDepth);
        }
      }
    }
  }
Ejemplo n.º 17
0
 private void determineValueSelectExpressions(
     QueryableCollection collectionPersister, List selections) {
   AliasGenerator aliasGenerator = new LocalAliasGenerator(1);
   appendSelectExpressions(
       collectionPersister.getElementColumnNames(), selections, aliasGenerator);
   Type valueType = collectionPersister.getElementType();
   if (valueType.isAssociationType()) {
     EntityType valueEntityType = (EntityType) valueType;
     Queryable valueEntityPersister =
         (Queryable) sfi().getEntityPersister(valueEntityType.getAssociatedEntityName(sfi()));
     SelectFragment fragment =
         valueEntityPersister.propertySelectFragmentFragment(elementTableAlias(), null, false);
     appendSelectExpressions(fragment, selections, aliasGenerator);
   }
 }
Ejemplo n.º 18
0
  protected String generateTableAlias(int n, PropertyPath path, Joinable joinable) {
    // TODO: deal with side-effects (changes to includeInResultRowList, userAliasList,
    // resultTypeList)!!!

    // for collection-of-entity, we are called twice for given "path"
    // once for the collection Joinable, once for the entity Joinable.
    // the second call will/must "consume" the alias + perform side effects according to
    // consumesEntityAlias()
    // for collection-of-other, however, there is only one call
    // it must "consume" the alias + perform side effects, despite what consumeEntityAlias() return
    // says
    //
    // note: the logic for adding to the userAliasList is still strictly based on
    // consumesEntityAlias return value
    boolean checkForSqlAlias = joinable.consumesEntityAlias();

    if (!checkForSqlAlias && joinable.isCollection()) {
      // is it a collection-of-other (component or value) ?
      CollectionPersister collectionPersister = (CollectionPersister) joinable;
      Type elementType = collectionPersister.getElementType();
      if (elementType.isComponentType() || !elementType.isEntityType()) {
        checkForSqlAlias = true;
      }
    }

    String sqlAlias = null;

    if (checkForSqlAlias) {
      final Criteria subcriteria = translator.getCriteria(path.getFullPath());
      sqlAlias = subcriteria == null ? null : translator.getSQLAlias(subcriteria);

      if (joinable.consumesEntityAlias() && !translator.hasProjection()) {
        includeInResultRowList.add(subcriteria != null && subcriteria.getAlias() != null);
        if (sqlAlias != null) {
          if (subcriteria.getAlias() != null) {
            userAliasList.add(subcriteria.getAlias());
            resultTypeList.add(translator.getResultType(subcriteria));
          }
        }
      }
    }

    if (sqlAlias == null) {
      sqlAlias = super.generateTableAlias(n + translator.getSQLAliasCount(), path, joinable);
    }

    return sqlAlias;
  }
Ejemplo n.º 19
0
  /** For a collection role, return a list of associations to be fetched by outerjoin */
  private void walkCollectionTree(
      final QueryableCollection persister,
      final String alias,
      final PropertyPath path,
      final int currentDepth)
      throws MappingException {

    if (persister.isOneToMany()) {
      walkEntityTree(
          (OuterJoinLoadable) persister.getElementPersister(), alias, path, currentDepth);
    } else {
      Type type = persister.getElementType();
      if (type.isAssociationType()) {
        // a many-to-many;
        // decrement currentDepth here to allow join across the association table
        // without exceeding MAX_FETCH_DEPTH (i.e. the "currentDepth - 1" bit)
        AssociationType associationType = (AssociationType) type;
        String[] aliasedLhsColumns = persister.getElementColumnNames(alias);
        String[] lhsColumns = persister.getElementColumnNames();
        // if the current depth is 0, the root thing being loaded is the
        // many-to-many collection itself.  Here, it is alright to use
        // an inner join...
        boolean useInnerJoin = currentDepth == 0;
        final JoinType joinType =
            getJoinType(
                associationType,
                persister.getFetchMode(),
                path,
                persister.getTableName(),
                lhsColumns,
                !useInnerJoin,
                currentDepth - 1,
                null // operations which cascade as far as the collection also cascade to collection
                     // elements
                );
        addAssociationToJoinTreeIfNecessary(
            associationType, aliasedLhsColumns, alias, path, currentDepth - 1, joinType);
      } else if (type.isComponentType()) {
        walkCompositeElementTree(
            (CompositeType) type,
            persister.getElementColumnNames(),
            persister,
            alias,
            path,
            currentDepth);
      }
    }
  }
 public boolean needsUpdating(Object entry, int i, Type elemType) throws HibernateException {
   Serializable sn = getSnapshot();
   return i < Array.getLength(sn)
       && Array.get(sn, i) != null
       && Array.get(array, i) != null
       && elemType.isDirty(Array.get(array, i), Array.get(sn, i), getSession());
 }
Ejemplo n.º 21
0
 public int generateHashCode(SessionFactoryImplementor factory) {
   int result = 17;
   result = 37 * result + entityName.hashCode();
   result = 37 * result + uniqueKeyName.hashCode();
   result = 37 * result + keyType.getHashCode(key, factory);
   return result;
 }
 private GridType getUniqueKeyTypeFromAssociatedEntity(int propertyIndex, String propertyName) {
   GridType
       gridUniqueKeyType; // get the unique key type and if it's an entity type, get it's
                          // identifier type
   final Type uniqueKeyType = getPropertyTypes()[propertyIndex];
   if (uniqueKeyType.isEntityType()) {
     // we run under the assumption that we are fully in an OGM world
     EntityType entityType = (EntityType) uniqueKeyType;
     final OgmEntityPersister entityPersister =
         (OgmEntityPersister) entityType.getAssociatedJoinable(getFactory());
     gridUniqueKeyType = entityPersister.getGridIdentifierType();
   } else {
     throw new AssertionFailure("loadByUniqueKey on a non EntityType:" + propertyName);
   }
   return gridUniqueKeyType;
 }
Ejemplo n.º 23
0
 @Override
 public boolean equalsSnapshot(CollectionPersister persister) throws HibernateException {
   final Type elementType = persister.getElementType();
   final java.util.Map sn = (java.util.Map) getSnapshot();
   if (sn.size() != set.size()) {
     return false;
   } else {
     for (Object test : set) {
       final Object oldValue = sn.get(test);
       if (oldValue == null || elementType.isDirty(oldValue, test, getSession())) {
         return false;
       }
     }
     return true;
   }
 }
Ejemplo n.º 24
0
 private String getElementName(
     PathExpressionParser.CollectionElement element, QueryTranslatorImpl q) throws QueryException {
   String name;
   if (element.isOneToMany) {
     name = element.alias;
   } else {
     Type type = element.elementType;
     if (type.isEntityType()) { // ie. a many-to-many
       String entityName = ((EntityType) type).getAssociatedEntityName();
       name = pathExpressionParser.continueFromManyToMany(entityName, element.elementColumns, q);
     } else {
       throw new QueryException("illegally dereferenced collection element");
     }
   }
   return name;
 }
  public void end(QueryTranslatorImpl q) throws QueryException {
    ignoreInitialJoin = false;

    Type propertyType = getPropertyType();
    if (propertyType != null && propertyType.isCollectionType()) {
      collectionRole = ((CollectionType) propertyType).getRole();
      collectionName = q.createNameForCollection(collectionRole);
      prepareForIndex(q);
    } else {
      columns = currentColumns();
      setType();
    }

    // important!!
    continuation = false;
  }
Ejemplo n.º 26
0
  public static void processDynamicFilterParameters(
      final String sqlFragment, final ParameterContainer container, final HqlSqlWalker walker) {
    if (walker.getEnabledFilters().isEmpty()
        && (!hasDynamicFilterParam(sqlFragment))
        && (!(hasCollectionFilterParam(sqlFragment)))) {
      return;
    }

    Dialect dialect = walker.getSessionFactoryHelper().getFactory().getDialect();
    String symbols =
        new StringBuffer()
            .append(ParserHelper.HQL_SEPARATORS)
            .append(dialect.openQuote())
            .append(dialect.closeQuote())
            .toString();
    StringTokenizer tokens = new StringTokenizer(sqlFragment, symbols, true);
    StringBuffer result = new StringBuffer();

    while (tokens.hasMoreTokens()) {
      final String token = tokens.nextToken();
      if (token.startsWith(ParserHelper.HQL_VARIABLE_PREFIX)) {
        final String filterParameterName = token.substring(1);
        final String[] parts = LoadQueryInfluencers.parseFilterParameterName(filterParameterName);
        final FilterImpl filter = (FilterImpl) walker.getEnabledFilters().get(parts[0]);
        final Object value = filter.getParameter(parts[1]);
        final Type type = filter.getFilterDefinition().getParameterType(parts[1]);
        final String typeBindFragment =
            StringHelper.join(
                ",",
                ArrayHelper.fillArray(
                    "?", type.getColumnSpan(walker.getSessionFactoryHelper().getFactory())));
        final String bindFragment =
            (value != null && Collection.class.isInstance(value))
                ? StringHelper.join(
                    ",", ArrayHelper.fillArray(typeBindFragment, ((Collection) value).size()))
                : typeBindFragment;
        result.append(bindFragment);
        container.addEmbeddedParameter(
            new DynamicFilterParameterSpecification(parts[0], parts[1], type));
      } else {
        result.append(token);
      }
    }

    container.setText(result.toString());
  }
 @Override
 public void setHibernateType(Type type) {
   if (type == null) {
     throw new IllegalArgumentException("Type cannot be null");
   }
   this.hibernateType = type;
   this.sqlTypes = hibernateType.sqlTypes(session().getFactory());
 }
Ejemplo n.º 28
0
 protected Serializable getResult(SessionImplementor session, ResultSet rs, Object entity)
     throws SQLException {
   if (!rs.next()) {
     throw new IdentifierGenerationException(
         "the inserted row could not be located by the unique key: " + uniqueKeyPropertyName);
   }
   return (Serializable)
       idType.nullSafeGet(rs, persister.getRootTableKeyColumnNames(), session, entity);
 }
Ejemplo n.º 29
0
 @Override
 @SuppressWarnings("unchecked")
 public boolean needsInserting(Object entry, int i, Type elemType) throws HibernateException {
   final Object oldValue = ((java.util.Map) getSnapshot()).get(entry);
   // note that it might be better to iterate the snapshot but this is safe,
   // assuming the user implements equals() properly, as required by the Set
   // contract!
   return oldValue == null || elemType.isDirty(oldValue, entry, getSession());
 }
  protected void initPropertyPaths(
      final String path,
      final Type type,
      String[] columns,
      final String[] formulaTemplates,
      final Mapping factory)
      throws MappingException {

    if (columns.length != type.getColumnSpan(factory)) {
      throw new MappingException("broken column mapping for: " + path + " of: " + getEntityName());
    }

    if (type.isAssociationType()) {
      AssociationType actype = (AssociationType) type;
      if (actype.useLHSPrimaryKey()) {
        columns = getIdentifierColumnNames();
      } else {
        String foreignKeyProperty = actype.getLHSPropertyName();
        if (foreignKeyProperty != null && !path.equals(foreignKeyProperty)) {
          // TODO: this requires that the collection is defined after the
          //      referenced property in the mapping file (ok?)
          columns = (String[]) columnsByPropertyPath.get(foreignKeyProperty);
          if (columns == null) return; // get em on the second pass!
        }
      }
    }

    if (path != null) addPropertyPath(path, type, columns, formulaTemplates);

    if (type.isComponentType()) {
      AbstractComponentType actype = (AbstractComponentType) type;
      initComponentPropertyPaths(path, actype, columns, formulaTemplates, factory);
      if (actype.isEmbedded()) {
        initComponentPropertyPaths(
            path == null ? null : StringHelper.qualifier(path),
            actype,
            columns,
            formulaTemplates,
            factory);
      }
    } else if (type.isEntityType()) {
      initIdentifierPropertyPaths(path, (EntityType) type, columns, factory);
    }
  }