/** * INTERNAL: This methods clones all the fields and ensures that each collection refers to the * same clones. */ @Override public Object clone() { VariableOneToOneMapping clone = (VariableOneToOneMapping) super.clone(); Map setOfKeys = new HashMap(getSourceToTargetQueryKeyNames().size()); Map sourceToTarget = new HashMap(getSourceToTargetQueryKeyNames().size()); Vector foreignKeys = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance( getForeignKeyFields().size()); if (getTypeField() != null) { clone.setTypeField((DatabaseField) this.getTypeField().clone()); } for (Iterator enumtr = getSourceToTargetQueryKeyNames().keySet().iterator(); enumtr.hasNext(); ) { // Clone the SourceKeyFields DatabaseField field = (DatabaseField) enumtr.next(); DatabaseField clonedField = (DatabaseField) field.clone(); setOfKeys.put(field, clonedField); // on the next line I'm cloning the query key names sourceToTarget.put(clonedField, getSourceToTargetQueryKeyNames().get(field)); } for (Enumeration enumtr = getForeignKeyFields().elements(); enumtr.hasMoreElements(); ) { DatabaseField field = (DatabaseField) enumtr.nextElement(); foreignKeys.addElement(setOfKeys.get(field)); } clone.setSourceToTargetQueryKeyFields(sourceToTarget); clone.setForeignKeyFields(foreignKeys); clone.setTypeIndicatorTranslation(new HashMap(this.getTypeIndicatorTranslation())); return clone; }
/** * INTERNAL: Build and return the appropriate field value for the specified set of nested rows. * The database better be expecting an ARRAY. It looks like we can ignore inheritance here.... */ public Object buildFieldValueFromNestedRows( Vector nestedRows, String structureName, AbstractSession session) throws DatabaseException { Object[] fields = new Object[nestedRows.size()]; java.sql.Connection connection = ((DatabaseAccessor) session.getAccessor()).getConnection(); boolean reconnected = false; try { if (connection == null) { ((DatabaseAccessor) session.getAccessor()).incrementCallCount(session); reconnected = true; connection = ((DatabaseAccessor) session.getAccessor()).getConnection(); } int i = 0; for (Enumeration stream = nestedRows.elements(); stream.hasMoreElements(); ) { AbstractRecord nestedRow = (AbstractRecord) stream.nextElement(); fields[i++] = this.buildStructureFromRow(nestedRow, session, connection); } return session.getPlatform().createArray(structureName, fields, session, connection); } catch (java.sql.SQLException exception) { throw DatabaseException.sqlException(exception, session, false); } finally { if (reconnected) { ((DatabaseAccessor) session.getAccessor()).decrementCallCount(); } } }
/** * INTERNAL: Return the value of the field from the row or a value holder on the query to obtain * the object. Check for batch + aggregation reading. */ @Override public Object valueFromRow( AbstractRecord row, JoinedAttributeManager joinManager, ObjectBuildingQuery sourceQuery, AbstractSession executionSession) throws DatabaseException { // If any field in the foreign key is null then it means there are no referenced objects for (Enumeration enumeration = getFields().elements(); enumeration.hasMoreElements(); ) { DatabaseField field = (DatabaseField) enumeration.nextElement(); if (row.get(field) == null) { return getIndirectionPolicy().nullValueFromRow(); } } if (getTypeField() != null) { // If the query used batched reading, return a special value holder, // or retrieve the object from the query property. if (sourceQuery.isReadAllQuery() && (((ReadAllQuery) sourceQuery).isAttributeBatchRead(getDescriptor(), getAttributeName()) || shouldUseBatchReading())) { return batchedValueFromRow(row, ((ReadAllQuery) sourceQuery)); } // If the field is empty we cannot load the object because we do not know what class it will // be if (row.get(getTypeField()) == null) { return getIndirectionPolicy().nullValueFromRow(); } Class implementerClass = (Class) getImplementorForType(row.get(getTypeField()), executionSession); ReadObjectQuery query = (ReadObjectQuery) getSelectionQuery().clone(); query.setReferenceClass(implementerClass); query.setSelectionCriteria(getSelectionCriteria()); query.setDescriptor(null); // Must set to null so the right descriptor is used if (sourceQuery.isObjectLevelReadQuery() && (sourceQuery.shouldCascadeAllParts() || (sourceQuery.shouldCascadePrivateParts() && isPrivateOwned()) || (sourceQuery.shouldCascadeByMapping() && this.cascadeRefresh))) { query.setShouldRefreshIdentityMapResult(sourceQuery.shouldRefreshIdentityMapResult()); query.setCascadePolicy(sourceQuery.getCascadePolicy()); query.setShouldMaintainCache(sourceQuery.shouldMaintainCache()); // For flashback. if (((ObjectLevelReadQuery) sourceQuery).hasAsOfClause()) { query.setAsOfClause(((ObjectLevelReadQuery) sourceQuery).getAsOfClause()); } // CR #4365 - used to prevent infinit recursion on refresh object cascade all query.setQueryId(sourceQuery.getQueryId()); } return getIndirectionPolicy().valueFromQuery(query, row, executionSession); } else { return super.valueFromRow(row, joinManager, sourceQuery, executionSession); } }
/** * PUBLIC: Return the foreign key field names associated with the mapping. These are only the * source fields that are writable. */ public Vector getForeignKeyFieldNames() { Vector fieldNames = new Vector(getForeignKeyFields().size()); for (Enumeration fieldsEnum = getForeignKeyFields().elements(); fieldsEnum.hasMoreElements(); ) { fieldNames.addElement(((DatabaseField) fieldsEnum.nextElement()).getQualifiedName()); } return fieldNames; }
/** PUBLIC: Set a collection of the source to target query key/field associations. */ public void setSourceToTargetQueryKeyFieldAssociations( Vector sourceToTargetQueryKeyFieldAssociations) { setSourceToTargetQueryKeyFields( new HashMap(sourceToTargetQueryKeyFieldAssociations.size() + 1)); for (Enumeration associationsEnum = sourceToTargetQueryKeyFieldAssociations.elements(); associationsEnum.hasMoreElements(); ) { Association association = (Association) associationsEnum.nextElement(); Object sourceField = new DatabaseField((String) association.getKey()); String targetQueryKey = (String) association.getValue(); getSourceToTargetQueryKeyNames().put(sourceField, targetQueryKey); } }
/** * PUBLIC: Return the foreign key field names associated with the mapping. These are only the * source fields that are writable. */ public void setForeignKeyFieldNames(Vector fieldNames) { Vector fields = org.eclipse.persistence.internal.helper.NonSynchronizedVector.newInstance( fieldNames.size()); for (Enumeration fieldNamesEnum = fieldNames.elements(); fieldNamesEnum.hasMoreElements(); ) { fields.addElement(new DatabaseField((String) fieldNamesEnum.nextElement())); } setForeignKeyFields(fields); if (!fields.isEmpty()) { setIsForeignKeyRelationship(true); } }
/** Append the string containing the SQL insert string for the given table. */ protected SQLCall buildCallWithoutReturning(AbstractSession session) { SQLCall call = new SQLCall(); call.returnNothing(); Writer writer = new CharArrayWriter(200); try { writer.write("INSERT "); if (getHintString() != null) { writer.write(getHintString()); writer.write(" "); } writer.write("INTO "); writer.write(getTable().getQualifiedNameDelimited(session.getPlatform())); writer.write(" ("); Vector fieldsForTable = new Vector(); for (Enumeration fieldsEnum = getModifyRow().keys(); fieldsEnum.hasMoreElements(); ) { DatabaseField field = (DatabaseField) fieldsEnum.nextElement(); if (field.getTable().equals(getTable()) || (!field.hasTableName())) { fieldsForTable.addElement(field); } } if (fieldsForTable.isEmpty()) { throw QueryException.objectToInsertIsEmpty(getTable()); } for (int i = 0; i < fieldsForTable.size(); i++) { writer.write( ((DatabaseField) fieldsForTable.elementAt(i)).getNameDelimited(session.getPlatform())); if ((i + 1) < fieldsForTable.size()) { writer.write(", "); } } writer.write(") VALUES ("); for (int i = 0; i < fieldsForTable.size(); i++) { DatabaseField field = (DatabaseField) fieldsForTable.elementAt(i); call.appendModify(writer, field); if ((i + 1) < fieldsForTable.size()) { writer.write(", "); } } writer.write(")"); call.setSQLString(writer.toString()); } catch (IOException exception) { throw ValidationException.fileError(exception); } return call; }
/** INTERNAL: Get a value from the object and set that in the respective field of the row. */ protected void writeFromNullObjectIntoRow(AbstractRecord record) { if (isReadOnly()) { return; } if (isForeignKeyRelationship()) { Enumeration foreignKeys = getForeignKeyFields().elements(); while (foreignKeys.hasMoreElements()) { record.put((DatabaseField) foreignKeys.nextElement(), null); } } if (getTypeField() != null) { record.put(getTypeField(), null); } }
/** PUBLIC: Set the class indicator associations. */ public void setClassIndicatorAssociations(Vector classIndicatorAssociations) { setTypeIndicatorNameTranslation(new HashMap(classIndicatorAssociations.size() + 1)); setTypeIndicatorTranslation(new HashMap((classIndicatorAssociations.size() * 2) + 1)); for (Enumeration associationsEnum = classIndicatorAssociations.elements(); associationsEnum.hasMoreElements(); ) { Association association = (Association) associationsEnum.nextElement(); Object classValue = association.getKey(); if (classValue instanceof Class) { // 904 projects will be a class type. addClassIndicator((Class) association.getKey(), association.getValue()); } else { addClassNameIndicator((String) association.getKey(), association.getValue()); } } }
/** INTERNAL: Get a value from the object and set that in the respective field of the row. */ @Override public void writeFromObjectIntoRowForWhereClause( ObjectLevelModifyQuery query, AbstractRecord record) { if (isReadOnly()) { return; } Object object; if (query.isDeleteObjectQuery()) { object = query.getObject(); } else { object = query.getBackupClone(); } Object referenceObject = getRealAttributeValueFromObject(object, query.getSession()); if (referenceObject == null) { writeFromNullObjectIntoRow(record); } else { if (isForeignKeyRelationship()) { Enumeration sourceFields = getForeignKeyFields().elements(); ClassDescriptor descriptor = query.getSession().getDescriptor(referenceObject.getClass()); while (sourceFields.hasMoreElements()) { DatabaseField sourceKey = (DatabaseField) sourceFields.nextElement(); String targetQueryKey = (String) getSourceToTargetQueryKeyNames().get(sourceKey); DatabaseField targetKeyField = descriptor.getObjectBuilder().getFieldForQueryKeyName(targetQueryKey); if (targetKeyField == null) { throw DescriptorException.variableOneToOneMappingIsNotDefinedProperly( this, descriptor, targetQueryKey); } Object referenceValue = descriptor .getObjectBuilder() .extractValueFromObjectForField( referenceObject, targetKeyField, query.getSession()); record.put(sourceKey, referenceValue); } } if (getTypeField() != null) { record.put(getTypeField(), getTypeForImplementor(referenceObject.getClass())); } } }
/** * INTERNAL: Get a value from the object and set that in the respective field of the row. If the * mapping id target foreign key, you must only write the type into the roe, the rest will be * updated when the object itself is written */ @Override public void writeFromObjectIntoRowWithChangeRecord( ChangeRecord changeRecord, AbstractRecord record, AbstractSession session) { if (isReadOnly()) { return; } ObjectChangeSet changeSet = (ObjectChangeSet) ((ObjectReferenceChangeRecord) changeRecord).getNewValue(); if (changeSet == null) { writeFromNullObjectIntoRow(record); } else { Object referenceObject = changeSet.getUnitOfWorkClone(); if (isForeignKeyRelationship()) { Enumeration sourceFields = getForeignKeyFields().elements(); ClassDescriptor descriptor = session.getDescriptor(referenceObject.getClass()); while (sourceFields.hasMoreElements()) { DatabaseField sourceKey = (DatabaseField) sourceFields.nextElement(); String targetQueryKey = (String) getSourceToTargetQueryKeyNames().get(sourceKey); DatabaseField targetKeyField = descriptor.getObjectBuilder().getFieldForQueryKeyName(targetQueryKey); if (targetKeyField == null) { throw DescriptorException.variableOneToOneMappingIsNotDefinedProperly( this, descriptor, targetQueryKey); } Object referenceValue = descriptor .getObjectBuilder() .extractValueFromObjectForField(referenceObject, targetKeyField, session); record.put(sourceKey, referenceValue); } } if (getTypeField() != null) { record.put(getTypeField(), getTypeForImplementor(referenceObject.getClass())); } } }
/** * INTERNAL: Return the value for in memory comparison. This is only valid for valueable * expressions. */ public Object valueFromObject( Object object, AbstractSession session, AbstractRecord translationRow, int valueHolderPolicy, boolean isObjectUnregistered) { // The expression may be across a relationship, in which case it must be traversed. if ((!getBaseExpression().isExpressionBuilder()) && getBaseExpression().isQueryKeyExpression()) { object = getBaseExpression() .valueFromObject( object, session, translationRow, valueHolderPolicy, isObjectUnregistered); // toDo: Null means the join filters out the row, returning null is not correct if an inner // join, // outer/inner joins need to be fixed to filter correctly. if (object == null) { return null; } // If from an anyof the object will be a collection of values, // A new vector must union the object values and the values extracted from it. if (object instanceof Vector) { Vector comparisonVector = new Vector(((Vector) object).size() + 2); for (Enumeration valuesToIterate = ((Vector) object).elements(); valuesToIterate.hasMoreElements(); ) { Object vectorObject = valuesToIterate.nextElement(); if (vectorObject == null) { comparisonVector.addElement(vectorObject); } else { Object valueOrValues = valuesFromCollection( vectorObject, session, valueHolderPolicy, isObjectUnregistered); // If a collection of values were extracted union them. if (valueOrValues instanceof Vector) { for (Enumeration nestedValuesToIterate = ((Vector) valueOrValues).elements(); nestedValuesToIterate.hasMoreElements(); ) { comparisonVector.addElement(nestedValuesToIterate.nextElement()); } } else { comparisonVector.addElement(valueOrValues); } } } return comparisonVector; } } return valuesFromCollection(object, session, valueHolderPolicy, isObjectUnregistered); }
/** INTERNAL: Conform the result if specified. */ protected Object conformResult( Object result, UnitOfWorkImpl unitOfWork, AbstractRecord arguments, boolean buildDirectlyFromRows) { if (getSelectionCriteria() != null) { ExpressionBuilder builder = getSelectionCriteria().getBuilder(); builder.setSession(unitOfWork.getRootSession(null)); builder.setQueryClass(getReferenceClass()); } // If the query is redirected then the collection returned might no longer // correspond to the original container policy. CR#2342-S.M. ContainerPolicy cp; if (getRedirector() != null) { cp = ContainerPolicy.buildPolicyFor(result.getClass()); } else { cp = getContainerPolicy(); } // This code is now a great deal different... For one, registration is done // as part of conforming. Also, this should only be called if one actually // is conforming. // First scan the UnitOfWork for conforming instances. // This will walk through the entire cache of registered objects. // Let p be objects from result not in the cache. // Let c be objects from cache. // Presently p intersect c = empty set, but later p subset c. // By checking cache now doesConform will be called p fewer times. Map indexedInterimResult = unitOfWork.scanForConformingInstances( getSelectionCriteria(), getReferenceClass(), arguments, this); Cursor cursor = null; // In the case of cursors just conform/register the initially read collection. if (cp.isCursorPolicy()) { cursor = (Cursor) result; cp = ContainerPolicy.buildPolicyFor(ClassConstants.Vector_class); // In nested UnitOfWork session might have been session of the parent. cursor.setSession(unitOfWork); result = cursor.getObjectCollection(); // for later incremental conforming... cursor.setInitiallyConformingIndex(indexedInterimResult); cursor.setSelectionCriteriaClone(getSelectionCriteria()); cursor.setTranslationRow(arguments); } // Now conform the result from the database. // Remove any deleted or changed objects that no longer conform. // Deletes will only work for simple queries, queries with or's or anyof's may not return // correct results when untriggered indirection is in the model. Vector fromDatabase = null; // When building directly from rows, one of the performance benefits // is that we no longer have to wrap and then unwrap the originals. // result is just a vector, not a container of wrapped originals. if (buildDirectlyFromRows) { Vector rows = (Vector) result; fromDatabase = new Vector(rows.size()); for (int i = 0; i < rows.size(); i++) { Object object = rows.elementAt(i); // null is placed in the row collection for 1-m joining to filter duplicate rows. if (object != null) { Object clone = conformIndividualResult( object, unitOfWork, arguments, getSelectionCriteria(), indexedInterimResult, buildDirectlyFromRows); if (clone != null) { fromDatabase.addElement(clone); } } } } else { fromDatabase = new Vector(cp.sizeFor(result)); AbstractSession sessionToUse = unitOfWork.getParent(); for (Object iter = cp.iteratorFor(result); cp.hasNext(iter); ) { Object object = cp.next(iter, sessionToUse); Object clone = conformIndividualResult( object, unitOfWork, arguments, getSelectionCriteria(), indexedInterimResult, buildDirectlyFromRows); if (clone != null) { fromDatabase.addElement(clone); } } } // Now add the unwrapped conforming instances into an appropriate container. // Wrapping is done automatically. // Make sure a vector of exactly the right size is returned. Object conformedResult = cp.containerInstance(indexedInterimResult.size() + fromDatabase.size()); Object eachClone; for (Iterator enumtr = indexedInterimResult.values().iterator(); enumtr.hasNext(); ) { eachClone = enumtr.next(); cp.addInto(eachClone, conformedResult, unitOfWork); } for (Enumeration enumtr = fromDatabase.elements(); enumtr.hasMoreElements(); ) { eachClone = enumtr.nextElement(); cp.addInto(eachClone, conformedResult, unitOfWork); } if (cursor != null) { cursor.setObjectCollection((Vector) conformedResult); // For nested UOW must copy all in object collection to // initiallyConformingIndex, as some of these could have been from // the parent UnitOfWork. if (unitOfWork.isNestedUnitOfWork()) { for (Enumeration enumtr = cursor.getObjectCollection().elements(); enumtr.hasMoreElements(); ) { Object clone = enumtr.nextElement(); indexedInterimResult.put(clone, clone); } } return cursor; } else { return conformedResult; } }
/** INTERNAL: */ public void validationAfterDescriptorInitialization(AbstractSession session) { Hashtable mapped = new Hashtable(); for (int operation = INSERT; operation <= UPDATE; operation++) { if ((main[operation][MAPPED] != null) && !main[operation][MAPPED].isEmpty()) { Iterator it = main[operation][MAPPED].iterator(); while (it.hasNext()) { DatabaseField field = (DatabaseField) it.next(); mapped.put(field, field); } } } if (!mapped.isEmpty()) { for (Enumeration fields = getDescriptor().getFields().elements(); fields.hasMoreElements(); ) { DatabaseField fieldInDescriptor = (DatabaseField) fields.nextElement(); DatabaseField fieldInMain = (DatabaseField) mapped.get(fieldInDescriptor); if (fieldInMain != null) { if (fieldInMain.getType() == null) { if (getDescriptor().isReturnTypeRequiredForReturningPolicy()) { session .getIntegrityChecker() .handleError( DescriptorException.returningPolicyMappedFieldTypeNotSet( fieldInMain.getName(), getDescriptor())); } } else if (isThereATypeConflict(fieldInMain, fieldInDescriptor)) { session .getIntegrityChecker() .handleError( DescriptorException.returningPolicyAndDescriptorFieldTypeConflict( fieldInMain.getName(), fieldInMain.getType().getName(), fieldInDescriptor.getType().getName(), getDescriptor())); } } } } if (!(session.getDatasourcePlatform() instanceof DatabasePlatform)) { // don't attempt further diagnostics on non-relational platforms return; } WriteObjectQuery[] query = { getDescriptor().getQueryManager().getInsertQuery(), getDescriptor().getQueryManager().getUpdateQuery() }; String[] queryTypeName = {"InsertObjectQuery", "UpdateObjectQuery"}; for (int operation = INSERT; operation <= UPDATE; operation++) { if ((main[operation][ALL] != null) && !main[operation][ALL].isEmpty()) { // this operation requires some fields to be returned if ((query[operation] == null) || (query[operation].getDatasourceCall() == null)) { if (!session.getPlatform().canBuildCallWithReturning()) { session .getIntegrityChecker() .handleError( DescriptorException.noCustomQueryForReturningPolicy( queryTypeName[operation], Helper.getShortClassName(session.getPlatform()), getDescriptor())); } } else if (query[operation].getDatasourceCall() instanceof StoredProcedureCall) { // SQLCall with custom SQL calculates its outputRowFields later (in prepare() method) - // that's why SQLCall can't be verified here. DatabaseCall customCall = (DatabaseCall) query[operation].getDatasourceCall(); Enumeration outputRowFields = customCall.getOutputRowFields().elements(); Collection notFoundInOutputRow = createCollection(); notFoundInOutputRow.addAll(main[operation][ALL]); while (outputRowFields.hasMoreElements()) { notFoundInOutputRow.remove(outputRowFields.nextElement()); } if (!notFoundInOutputRow.isEmpty()) { Iterator it = notFoundInOutputRow.iterator(); while (it.hasNext()) { DatabaseField field = (DatabaseField) it.next(); session .getIntegrityChecker() .handleError( DescriptorException.customQueryAndReturningPolicyFieldConflict( field.getName(), queryTypeName[operation], getDescriptor())); } } } } } }
/** INTERNAL: */ public void initialize(AbstractSession session) { clearInitialization(); main = new Collection[NUM_OPERATIONS][MAIN_SIZE]; // The order of descriptor initialization guarantees initialization of Parent before children. // main array is copied from Parent's ReturningPolicy if (getDescriptor().isChildDescriptor()) { ClassDescriptor parentDescriptor = getDescriptor().getInheritancePolicy().getParentDescriptor(); if (parentDescriptor.hasReturningPolicy()) { copyMainFrom(parentDescriptor.getReturningPolicy()); } } if (!infos.isEmpty()) { Hashtable infoHashtable = removeDuplicateAndValidateInfos(session); Hashtable infoHashtableUnmapped = (Hashtable) infoHashtable.clone(); for (Enumeration fields = getDescriptor().getFields().elements(); fields.hasMoreElements(); ) { DatabaseField field = (DatabaseField) fields.nextElement(); Info info = (Info) infoHashtableUnmapped.get(field); if (info != null) { infoHashtableUnmapped.remove(field); if (verifyFieldAndMapping(session, field)) { if (info.getField().getType() == null) { addMappedFieldToMain(field, info); } else { addMappedFieldToMain(info.getField(), info); fieldIsNotFromDescriptor(info.getField()); } } } } if (!infoHashtableUnmapped.isEmpty()) { Enumeration fields = infoHashtableUnmapped.keys(); while (fields.hasMoreElements()) { DatabaseField field = (DatabaseField) fields.nextElement(); Info info = (Info) infoHashtableUnmapped.get(field); if (verifyField(session, field, getDescriptor())) { if (field.getType() != null) { addUnmappedFieldToMain(field, info); fieldIsNotFromDescriptor(field); session.log( SessionLog.FINEST, SessionLog.QUERY, "added_unmapped_field_to_returning_policy", info.toString(), getDescriptor().getJavaClassName()); } else { if (getDescriptor().isReturnTypeRequiredForReturningPolicy()) { session .getIntegrityChecker() .handleError( DescriptorException.returningPolicyUnmappedFieldTypeNotSet( field.getName(), getDescriptor())); } } } } } } initializeIsUsedToSetPrimaryKey(); }