Assumptions:
a) all operations in the set work on entities such that the entities implement {@link HasDbReferences}.
b) all operations in the set work on the same type (ie. all operations are INSERTs or DELETEs).
508403
protected List<DbEntityOperation> sortByReferences(SortedSet<DbEntityOperation> preSorted) {
    // copy the pre-sorted set and apply final sorting to list
    List<DbEntityOperation> opList = new ArrayList<DbEntityOperation>(preSorted);

    for (int i = 0; i < opList.size(); i++) {

      DbEntityOperation currentOperation = opList.get(i);
      DbEntity currentEntity = currentOperation.getEntity();
      Set<String> currentReferences = currentOperation.getFlushRelevantEntityReferences();

      // check whether this operation must be placed after another operation
      int moveTo = i;
      for(int k = i+1; k < opList.size(); k++) {
        DbEntityOperation otherOperation = opList.get(k);
        DbEntity otherEntity = otherOperation.getEntity();
        Set<String> otherReferences = otherOperation.getFlushRelevantEntityReferences();

        if(currentOperation.getOperationType() == INSERT) {


          // if we reference the other entity, we need to be inserted after that entity
          if(currentReferences != null && currentReferences.contains(otherEntity.getId())) {
            moveTo = k;
            break; // we can only reference a single entity
          }

        } else { // UPDATE or DELETE

          // if the other entity has a reference to us, we must be placed after the other entity
          if(otherReferences != null && otherReferences.contains(currentEntity.getId())) {
            moveTo = k;
            // cannot break, there may be another entity further to the right which also references us
          }

        }
      }

      if(moveTo > i) {
        opList.remove(i);
        opList.add(moveTo, currentOperation);
        i--;
      }
    }

    return opList;
  }
1164852
def dereference(self, session, ref, allow_none=False):
        
        ref = DBRef(id=ref, collection=self.type.type.get_collection_name(),
                    database=self.db)
        ref.type = self.type.type
        return session.dereference(ref, allow_none=allow_none)
155772
public boolean hasChanges() {
        for (Map.Entry<Object, DocumentInfo> entity : documentsByEntity.entrySet()) {
            ObjectNode document = entityToJson.convertEntityToJson(entity.getKey(), entity.getValue());
            if (entityChanged(document, entity.getValue(), null)) {
                return true;
            }
        }

        return !deletedEntities.isEmpty();
    }
272199
@Override
    public Set entrySet() {
        if (entrySet != null) {
            return entrySet;
        }
        entrySet = new AbstractSet() {
            @Override
            public int size() {
                return ReferenceMap.this.size();
            }


            @Override
            public void clear() {
                ReferenceMap.this.clear();
            }


            @Override
            public boolean contains(final Object o) {
                if (o == null) {
                    return false;
                }
                if (!(o instanceof Map.Entry)) {
                    return false;
                }
                final Map.Entry e = (Map.Entry) o;
                final Entry e2 = getEntry(e.getKey());
                return (e2 != null) && e.equals(e2);
            }


            @Override
            public boolean remove(final Object o) {
                final boolean r = contains(o);
                if (r) {
                    final Map.Entry e = (Map.Entry) o;
                    ReferenceMap.this.remove(e.getKey());
                }
                return r;
            }


            @Override
            public Iterator iterator() {
                return new EntryIterator();
            }

            @Override
            public Object[] toArray() {
                return toArray(new Object[0]);
            }


            @Override
            @SuppressWarnings("unchecked")
            public Object[] toArray(final Object[] arr) {
                final List list = new ArrayList();
                final Iterator iterator = iterator();
                while (iterator.hasNext()) {
                    final Entry e = (Entry) iterator.next();
                    list.add(new DefaultMapEntry(e.getKey(), e.getValue()));
                }
                return list.toArray(arr);
            }
        };
        return entrySet;
    }
169376
Optional<EntityDescriptor> referencingEntity(AttributeDescriptor attribute) {
        if (!Names.isEmpty(attribute.referencedTable())) {
            // match by table name
            return entities.values().stream()
                .filter(entity -> entity.tableName().equalsIgnoreCase(attribute.referencedTable()))
                .findFirst();

        } else if (!Names.isEmpty(attribute.referencedType())) {
            // match by type name
            Optional<TypeKind> primitiveType = Stream.of(TypeKind.values())
                .filter(TypeKind::isPrimitive)
                .filter(kind -> kind.toString().toLowerCase().equals(attribute.referencedType()))
                .findFirst();
            if (!primitiveType.isPresent()) {
                QualifiedName referencedType = new QualifiedName(attribute.referencedType());
                return entityByName(referencedType);
            } // else attribute is basic foreign key and not referring to an entity
        } else {
            TypeMirror referencedType = attribute.typeMirror();
            if (attribute.isIterable()) {
                referencedType = collectionElementType(referencedType);
            }
            TypeElement referencedElement = (TypeElement) types.asElement(referencedType);
            if (referencedElement != null) {
                String referencedName = referencedElement.getSimpleName().toString();
                return entities.values().stream()
                        .filter(entity -> match(entity, referencedName))
                        .findFirst();
            }
        }
        return Optional.empty();
    }
598863
private boolean isGuardedInstanceofReference(Node reference) {
    Node instanceofNode = reference.getParent();
    if (isInstanceofFor(instanceofNode, reference)) {
      Node andNode = instanceofNode.getParent();
      return andNode != null
          && andNode.isAnd()
          && isUndefinedTypeofGuardFor(andNode.getFirstChild(), reference);
    } else {
      return false;
    }
  }
1308124
public boolean addReference(ServiceReference<T> reference) {
        if (reference == null)
            return false;

        ConcurrentServiceReferenceElement<T> element = new ConcurrentServiceReferenceElement<T>(referenceName, reference);

        synchronized (elementMap) {
            ConcurrentServiceReferenceElement<T> oldElement = elementMap.put(reference, element);
            if (oldElement != null) {
                if (!element.getRanking().equals(oldElement.getRanking())) {
                    elementSetUnsorted = true;
                }
                return true;
            }

            elementSet.add(element);
        }
        return false;
    }
1176996
boolean canReference(Table table, boolean[] columnCheckList) {

        if (isFull || isFullReferences) {
            return true;
        }

        return containsAllColumns(referencesColumnSet, table, columnCheckList);
    }
591381
private boolean updateExistingObject(DBObject dbObj, Map<String, String> currScalarMap) {
        if (objectIsChangingShards(dbObj, currScalarMap)) {
            return updateShardedObjectMove(dbObj);
        } else {
            return updateObjectSameShard(dbObj, currScalarMap);
        }
    }
742237
public static void setExpandEntityReferences(boolean b) {
        expandEntities = b;
        getControlDocumentBuilderFactory().setExpandEntityReferences(b);
        getTestDocumentBuilderFactory().setExpandEntityReferences(b);
    }
1008313
public CandidateReference instantiateForInsert() {
		CandidateReference entity = new CandidateReference();
		entity.setIsDeleted(Boolean.FALSE);
		entity.setCandidate(new Candidate(1));
		return entity;
	}
765659
public boolean isBOF()
    {
        boolean bFlag = ((m_iRecordStatus & DBConstants.RECORD_AT_BOF) != 0);
        if (this.isTable())
        {   // If this is a table, it can't handle starting and ending keys.. do it manually
            if (bFlag)
                return bFlag;
            if (this.getRecord().getKeyArea(-1).isModified(DBConstants.START_SELECT_KEY))
            {
                if (!bFlag)
                    bFlag = this.getRecord().checkParams(DBConstants.START_SELECT_KEY);
                if (bFlag)
                    m_iRecordStatus |= DBConstants.RECORD_AT_BOF; // At BOF
            }
        }
        return bFlag;
    }
213746
private boolean hasBidirectionalAssociation(Class clazz)
    {
        ClassDescriptor cdesc;
        Collection refs;
        boolean hasBidirAssc;

        if (_withoutBidirAssc.contains(clazz))
        {
            return false;
        }

        if (_withBidirAssc.contains(clazz))
        {
            return true;
        }

        // first time we meet this class, let's look at metadata
        cdesc = _pb.getClassDescriptor(clazz);
        refs = cdesc.getObjectReferenceDescriptors();
        hasBidirAssc = false;
        REFS_CYCLE:
        for (Iterator it = refs.iterator(); it.hasNext(); )
        {
            ObjectReferenceDescriptor ord;
            ClassDescriptor relCDesc;
            Collection relRefs;

            ord = (ObjectReferenceDescriptor) it.next();
            relCDesc = _pb.getClassDescriptor(ord.getItemClass());
            relRefs = relCDesc.getObjectReferenceDescriptors();
            for (Iterator relIt = relRefs.iterator(); relIt.hasNext(); )
            {
                ObjectReferenceDescriptor relOrd;

                relOrd = (ObjectReferenceDescriptor) relIt.next();
                if (relOrd.getItemClass().equals(clazz))
                {
                    hasBidirAssc = true;
                    break REFS_CYCLE;
                }
            }
        }
        if (hasBidirAssc)
        {
            _withBidirAssc.add(clazz);
        }
        else
        {
            _withoutBidirAssc.add(clazz);
        }

        return hasBidirAssc;
    }
824171
@Override
  protected void deleteEntity(DbEntityOperation operation) {

    final DbEntity dbEntity = operation.getEntity();

    // get statement
    String deleteStatement = dbSqlSessionFactory.getDeleteStatement(dbEntity.getClass());
    ensureNotNull("no delete statement for " + dbEntity.getClass() + " in the ibatis mapping files", "deleteStatement", deleteStatement);

    LOG.executeDatabaseOperation("DELETE", dbEntity);

    // execute the delete
    int nrOfRowsDeleted = executeDelete(deleteStatement, dbEntity);
    operation.setRowsAffected(nrOfRowsDeleted);

    // It only makes sense to check for optimistic locking exceptions for objects that actually have a revision
    if (dbEntity instanceof HasDbRevision && nrOfRowsDeleted == 0) {
      operation.setFailed(true);
      return;
    }

    // perform post delete action
    entityDeleted(dbEntity);
  }
125826
protected void addSortedInserts(List<DbOperation> flush) {
    for (Entry<Class<?>, SortedSet<DbEntityOperation>> operationsForType : inserts.entrySet()) {

      // add inserts to flush
      if(HasDbReferences.class.isAssignableFrom(operationsForType.getKey())) {
        // if this type has self references, we need to resolve the reference order
        flush.addAll(sortByReferences(operationsForType.getValue()));
      } else {
        flush.addAll(operationsForType.getValue());
      }
    }
  }
646819
@Override
    public DBObject getUpdateClause() {
        if (clear) {
            // If new items were added, they'll be placed on the updateList.  Either way We use $set to ensure old
            // values are removed from the underlying store.
            BasicDBList updateList = new BasicDBList();
            updateList.addAll(updates);

            return new BasicDBObject($set.name(), new BasicDBObject(getNameFromPrefix(),  updateList));
        } else {
            if (updates.isEmpty()) {
                return new BasicDBObject();     // If there are no updates, return an empty DBObject
            } else {
                BasicDBList updateList = new BasicDBList();
                updateList.addAll(updates);
                
                if (operation.equals($addToSet)) {
                    return new BasicDBObject($addToSet.name(), new BasicDBObject(getNameFromPrefix(), new BasicDBObject(EACH, updateList)));
                } else {
                    return new BasicDBObject(operation.name(), new BasicDBObject(getNameFromPrefix(), updateList));
                }
            }
        }
    }
647189
private boolean hasOperationOfType(SQLiteDatabaseSchema schema, MethodSpec.Builder methodBuilder, JQLType jqlType) {
		boolean hasOperation = false;
		for (SQLiteDaoDefinition daoDefinition : schema.getCollection()) {

			if (daoDefinition.getElement().getAnnotation(BindContentProviderPath.class) == null)
				continue;

			for (SQLiteModelMethod daoMethod : daoDefinition.getCollection()) {
				if (daoMethod.jql.operationType != jqlType) {
					continue;
				}
				if (!daoMethod.hasAnnotation(BindContentProviderEntry.class)) {
					continue;
				}

				hasOperation = true;
				// methodBuilder.addJavadoc("method $L.$L\n",
				// daoDefinition.getName(), daoMethod.getName());
			}
		}
		return hasOperation;
	}