Not well-suited to factor out into an interface method since for JPA it's embedded in a tran typically
349448
private TopLevelStepExecutionEntity getStepExecutionTopLevelFromJobExecutionIdAndStepName(long jobExecutionId, String stepName) {
        JobExecutionEntity jobExecution = data.executionInstanceData.get(jobExecutionId);
        // Copy list to avoid ConcurrentModificationException
        for (StepThreadExecutionEntity stepExec : new ArrayList<StepThreadExecutionEntity>(jobExecution.getStepThreadExecutions())) {
            if (stepExec.getStepName().equals(stepName)) {
                if (stepExec instanceof TopLevelStepExecutionEntity) {
                    return (TopLevelStepExecutionEntity) stepExec;
                }
            }
        }
        // Bad if we've gotten here.
        throw new IllegalStateException("Couldn't find top-level step execution for jobExecution = " + jobExecutionId + ", and stepName = " + stepName);
    }
857416
public static void javaProperty2WhereCondition(MethodSpec.Builder methodBuilder, SQLiteModelMethod method,
			String paramName, TypeName paramType, ModelProperty property) {
		if (property != null && property.hasTypeAdapter()) {
			methodBuilder.addCode(
					AbstractSQLTransform.PRE_TYPE_ADAPTER_TO_STRING + "$L" + AbstractSQLTransform.POST_TYPE_ADAPTER,
					SQLTypeAdapterUtils.class, typeName(property.typeAdapter.adapterClazz),
					PropertyUtility.getter(paramName, paramType, property));
		} else if (property != null) {
			SQLTransform transform = lookup(property.getPropertyType().getTypeName());

			AssertKripton.assertTrueOrUnsupportedFieldTypeException(transform != null, paramType);
			transform.generateWriteProperty2WhereCondition(methodBuilder, paramName, paramType, property);
		} else {
			AssertKripton.assertTrueOrUnsupportedFieldTypeException(false, paramType);
		}
	}
1179403
private Object resolveBean(String name, Class<?> type)
   {
      try
      {
         return embedded.lookup(name, type);
      }
      catch (Throwable t)
      {
         return null;
      }
   }
632957
private static <T extends Annotation, R> Builder<R> getAnnotatedInstances(
            AnnotatedElement method, AnnotatedElement clazz, Class<T> annotationType, Class<R> resultType) {
        final Builder<R> builder = new Builder<>();
        Stream.concat(findAll(method, annotationType).stream(),
                      findAll(clazz, annotationType).stream())
              .forEach(annotation -> builder.add(getInstance(annotation, resultType)));
        return builder;
    }
932401
private static void onEmbeddable(EntityType entityType, Attribute column, Object entity,
            EmbeddableType embeddableType, JsonObject jsonObject)
    {
        Object embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());
        String embeddedColumnName = ((AbstractAttribute) column).getJPAColumnName();
        Set<Attribute> embeddableAttributes = embeddableType.getAttributes();
        jsonObject.add(embeddedColumnName, getJsonObject(embeddableAttributes, embeddedObject));
    }
7203
@Bean
	public JpaModule jpaModule() {
		JpaModule module = JpaModule.newServerModule(em, transactionRunner);

		// directly expose entity
		module.addRepository(JpaRepositoryConfig.builder(ScheduleEntity.class).build());

		// additionally expose entity as a mapped dto
		module.addRepository(JpaRepositoryConfig.builder(ScheduleEntity.class, ScheduleDto.class, new ScheduleMapper()).build());
		JpaCriteriaQueryFactory queryFactory = (JpaCriteriaQueryFactory) module.getQueryFactory();

		// register a computed a attribute
		// you may consider QueryDSL or generating the Criteria query objects.
		queryFactory.registerComputedAttribute(ScheduleEntity.class, "upperName", String.class,
				new JpaCriteriaExpressionFactory<From<?, ScheduleEntity>>() {

					@SuppressWarnings({ "rawtypes", "unchecked" })
					@Override
					public Expression<String> getExpression(From<?, ScheduleEntity> entity, CriteriaQuery<?> query) {
						CriteriaBuilder builder = em.getCriteriaBuilder();
						return builder.upper((Expression) entity.get("name"));
					}
				});
		return module;
	}
467300
private EJBMethodInfoImpl mapMethodInfo(EJSDeployedSupport s,
                                            EJSWrapperBase wrapper, int methodId,
                                            String methodSignature) {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); // d532639.2

        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "mapMethodInfo(" + methodId + "," + methodSignature + ")");

        EJBMethodInfoImpl rtnInfo = null; // d122418-1 //d140003.20

        s.methodId = methodId; //130230 d140003.19
        s.ivWrapper = wrapper; // d366807.1

        if (methodId < 0) {
            if (methodId == MID_BUSINESS_REMOVE) {
                // Internal remove method for business interfaces.        F743-29185
                rtnInfo = s.ivThreadData.getEJBMethodInfoStack().get(
                                                                     "$remove:", null, wrapper,
                                                                     wrapper.ivInterface == WrapperInterface.BUSINESS_LOCAL ? MethodInterface.LOCAL : MethodInterface.REMOTE,
                                                                     wrapper.bmd.usesBeanManagedTx ? TransactionAttribute.TX_BEAN_MANAGED : TransactionAttribute.TX_NOT_SUPPORTED);
                rtnInfo.setClassLoader = true; // d661827
            } else {
                rtnInfo = ivEntityHelper.getPMMethodInfo(s, wrapper, methodId, methodSignature);
            }
        } else // d122418-1
        { // d122418-1
          // d206696 - Account for case where
          // methodInfos array is null (which occurs if WS invocation
          // API is used on an SLSB with no service endpoint interface defined)
            if (wrapper.methodInfos == null)
                throw new IllegalStateException("An attempt was made to invoke a method on a bean interface that is not defined.");
            rtnInfo = wrapper.methodInfos[methodId]; // d122418-1
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "mapMethodInfo");

        return rtnInfo; // d122418-1
    }
40643
private JClassType extractMappedType( JClassType interfaceClass ) throws UnableToCompleteException {
        JClassType intf = interfaceClass.isInterface();
        if ( intf == null ) {
            logger.log( TreeLogger.Type.ERROR, "Expected " + interfaceClass + " to be an interface." );
            throw new UnableToCompleteException();
        }

        JClassType[] intfs = intf.getImplementedInterfaces();
        for ( JClassType t : intfs ) {
            if ( t.getQualifiedSourceName().equals( OBJECT_MAPPER_CLASS ) ) {
                return extractParameterizedType( OBJECT_MAPPER_CLASS, t.isParameterized() );
            } else if ( t.getQualifiedSourceName().equals( OBJECT_READER_CLASS ) ) {
                return extractParameterizedType( OBJECT_READER_CLASS, t.isParameterized() );
            } else if ( t.getQualifiedSourceName().equals( OBJECT_WRITER_CLASS ) ) {
                return extractParameterizedType( OBJECT_WRITER_CLASS, t.isParameterized() );
            }
        }
        logger.log( TreeLogger.Type.ERROR, "Expected  " + interfaceClass + " to extend one of the following interface : " +
                OBJECT_MAPPER_CLASS + ", " + OBJECT_READER_CLASS + " or " + OBJECT_WRITER_CLASS );
        throw new UnableToCompleteException();
    }
1198350
public static void javaProperty2ContentValues(MethodSpec.Builder methodBuilder, TypeName beanClass, String beanName,
			ModelProperty property) {
		TypeName typeName = null;

		if (property != null && property.getPropertyType() != null) {
			typeName = property.getPropertyType().getTypeName();
		}

		if (property != null && property.hasTypeAdapter()) {
			typeName = typeName(property.typeAdapter.dataType);
		}
		SQLTransform transform = lookup(typeName);

		AssertKripton.assertTrueOrUnsupportedFieldTypeException(transform != null, typeName);
		transform.generateWriteProperty2ContentValues(methodBuilder, beanName, beanClass, property);
	}
352905
@Override
    EntityManager getEMInvocationInfo(boolean requireTx, LockModeType mode)
    {
        UOWCoordinator uowCoord = ivAbstractJPAComponent.getUOWCurrent().getUOWCoord();
        SynchronizationRegistryUOWScope uowSyncRegistry = getSynchronizationRegistryUOWScope(uowCoord);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "getEMInvocationInfo : " + requireTx + " : tid=" + txIdToString(uowCoord));

        boolean globalTx = uowCoord.isGlobal();

        // The container must throw the TransactionRequiredException if a transaction-scoped
        // persistence context is used, and the EntityManager persist, remove, merge, or refresh
        // method is invoked when no transaction is active.
        if (!globalTx && (requireTx || (mode != null && !LockModeType.NONE.equals(mode)))) //d597764
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                Tr.exit(tc, "getEMInvocationInfo : TransactionRequiredException: " +
                            "No active transaction for " + ivPuRefId);

            // The provider is not responsible to throw this exception for
            //  persist, remove, refresh and merge methods since these methods are supported in
            //  extend-scoped persistence context. The "container" must enforced this
            //  rule per JPA spec.
            throw new TransactionRequiredException("No active transaction for " + ivPuRefId);
        }

        // (JPA 5.6.3.1 Requirements for Persistence Context Propagation)
        // Persistence contexts are propagated by the container across component invocations as follows.
        //
        // If a component is called and there is no JTA transaction or the JTA transaction is not
        // propagated, the persistence context is not propagated.
        // * If an entity manager is then invoked from within the component:
        // * Invocation of an entity manager defined with PersistenceContext-Type.TRANSACTION will
        //      result in use of a new persistence context (as described in section 5.6.1).
        // * Invocation of an entity manager defined with PersistenceContext-Type.EXTENDED will
        //      result in the use of the existing extended persistence context bound to that component.
        // * If the entity manager is invoked within a JTA transaction, the persistence context will
        //      be bound to the JTA transaction.
        //
        // If a component is called and the JTA transaction is propagated into that component:
        // * If the component is a stateful session bean to which an extended persistence context
        //      has been bound and there is a different persistence context bound to the JTA transaction,
        //      an EJBException is thrown by the container.
        // * Otherwise, if there is a persistence context bound to the JTA transaction, that
        //      persistence context is propagated and used.

        JPAExEmInvocation invocationEm = getInvocation(uowSyncRegistry, ivTxKeyPuId); // d683375, d689596
        if (invocationEm == null)
        {
            EntityManager em = ivEntityManagerPool.getEntityManager(globalTx, ivUnsynchronized); // d510184
            if (globalTx)
            {
                // 5.9.1 Container Responsibilities
                //  For the management of a transaction-scoped persistence context, if there is no
                //  EntityManager already associated with the JTA transaction:
                //  * The container creates a new entity manager by calling EntityManagerFactory.createEntityManager
                //      when the first invocation of an entity manager with PersistenceContextType.TRANSACTION
                //      occurs within the scope of a business method executing in the JTA transaction.
                //
                //  When the container creates an entity manager, it may pass a map of properties to the
                //      persistence provider by using the EntityManagerFactory.createEntityManager(Map map)
                //      method. If properties have been specified in the PersistenceContext annotation or
                //      the persistence-context-ref deployment descriptor element, this method must be
                //      used and the map must include the specified properties.

                JPATxEmInvocation txEmInvocation = createJPATxEmInvocation(uowCoord, em);

                // Register invocation object to transaction manager for clean up on commit/rollback.
                registerEmInvocation(uowCoord, txEmInvocation); //d638095.2

                invocationEm = txEmInvocation;
            }
            else
            {
                // 5.6.3.1 Requirements for Persistence Context Propagation
                // Persistence contexts are propagated by the container across component invocations as follows.
                // If a component is called and there is no JTA transaction or the JTA transaction is not propagated,
                //  the persistence context is not propagated.
                //  *   If an entity manager is then invoked from within the component:
                //      *   Invocation of an entity manager defined with PersistenceContext-Type.TRANSACTION will
                //          result in use of a new persistence context (as described in section 5.6.1).
                //
                // 5.9.1 Container Responsibilities
                // [39] The container may choose to pool EntityManagers and instead of creating and
                //      closing in each case acquire one from its pool and call clear() on it.

                // For a specific UnitOfWork a new JPANoTxEmInvocation object and
                // Entity Manager instance will be created.
                // The invocation objects will be registered with the UOW and held
                // in a map keyed by the UnitOfWork id so that the same invocation
                // and entity manager are used for the entire LTC or Activity Session.
                // Both the invocation object and Entity Manager instance will be pooled
                // or closed during afterCompletion processing of the UOW.

                JPANoTxEmInvocation noTxEmInvocation = createJPANoTxEmInvocation(uowCoord, em);

                // Register invocation object to transaction manager for clean up on commit/rollback.
                // Currently registration for local transactions is not Tiered.  This may need to change
                // if conflicts arise.  //d638095.4

                LocalTransactionCoordinator ltCoord = (LocalTransactionCoordinator) uowCoord;
                ltCoord.enlistSynchronization(noTxEmInvocation); // F61571

                invocationEm = noTxEmInvocation;
            }

            setInvocation(uowSyncRegistry, ivTxKeyPuId, invocationEm); // d683375, d689596
        } else {
            // JPA 2.1: 7.6.4.1 Requirements for Persistence Context Propagation
            // If a component is called and the JTA transaction is propagated into that component:
            //   * If there is a persistence context of type SynchronizationType.UNSYNCHRONIZED associated with the 
            //     JTA transaction and the target component specifies a persistence context of type 
            //     SynchronizationType.SYNCHRONIZED, the IllegalStateException is thrown by the container.
            if (invocationEm.isTxUnsynchronized() && !isTxUnsynchronized()) {
                Tr.error(tc, "JPATXSYNC_ILLEGAL_PROPAGATION_CWWJP0046E");
                String msgTxt = "CWWJP0046E: An UNSYNCHRONIZED JPA persistence context cannot be propagated into a SYNCHRONIZED EntityManager.";
                throw new IllegalStateException(msgTxt);
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "getEMInvocationInfo : " + invocationEm);
        return invocationEm;
    }
809713
private <T, Y> TypedQuery<T> createTypedQueryIn(Class<T> entityCls,
            SingularAttribute<T, Y> attribute, List<Y> values) {
        EntityManager entityManager = this.entityManagerProvider.get();
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<T> criteriaQuery = builder.createQuery(entityCls);
        Root<T> root = criteriaQuery.from(entityCls);
        Path<Y> path = root.get(attribute);
        CriteriaBuilder.In<Y> in = builder.in(path);
        if (values != null) {
            for (Y val : values) {
                in.value(val);
            }
        }
        return entityManager.createQuery(criteriaQuery.where(in));
    }
1116252
@Override
    public <T> TypedQuery<T> createQuery(CriteriaQuery<T> arg0) {
        try
        {
            return ivEm.createQuery(arg0);
        } finally
        {
            if (!inJTATransaction())
            {
                ivEm.clear();
            }
        }
    }
317403
public void generateJavaDoc(MethodSpec.Builder methodBuilder, final SQLiteModelMethod method, TypeName returnType,
			List<SQLProperty> listUsedProperty, ModelProperty primaryKey) {
		// transform JQL to SQL
		String sqlInsert = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public String onColumnName(String columnName) {
				Set<SQLProperty> property = currentSchema.getPropertyBySimpleName(columnName);

				SQLProperty tempProperty = property.iterator().next();
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);

				return tempProperty.columnName;
			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				String resolvedParamName = method.findParameterNameByAlias(bindParameterName);

				return SqlAnalyzer.PARAM_PREFIX + resolvedParamName + SqlAnalyzer.PARAM_SUFFIX;
			}

		});

		// generate javadoc and result
		{
			String beanNameParameter = method.findParameterAliasByName(method.getParameters().get(0).value0);

			methodBuilder.addJavadoc("<h2>SQL insert</h2>\n");
			methodBuilder.addJavadoc("<pre>$L</pre>\n\n", sqlInsert);
			methodBuilder.addJavadoc(
					"<p><code>$L.$L</code> is automatically updated because it is the primary key</p>\n",
					beanNameParameter, primaryKey.getName());
			methodBuilder.addJavadoc("\n");

			// list of inserted fields
			methodBuilder.addJavadoc("<p><strong>Inserted columns:</strong></p>\n");
			methodBuilder.addJavadoc("<dl>\n");
			for (SQLProperty property : listUsedProperty) {
				methodBuilder.addJavadoc("\t<dt>$L</dt>", property.columnName);
				methodBuilder.addJavadoc("<dd>is mapped to <strong>$L</strong></dd>\n",
						SqlAnalyzer.PARAM_PREFIX + method.findParameterAliasByName(method.getParameters().get(0).value0)
								+ "." + method.findParameterNameByAlias(property.getName()) + SqlAnalyzer.PARAM_SUFFIX);
			}
			methodBuilder.addJavadoc("</dl>\n\n");

			// update bean have only one parameter: the bean to update
			for (Pair<String, TypeName> param : method.getParameters()) {
				methodBuilder.addJavadoc("@param $L", param.value0);
				methodBuilder.addJavadoc("\n\tis mapped to parameter <strong>$L</strong>\n",
						method.findParameterAliasByName(param.value0));
			}

			InsertRawHelper.generateJavaDocReturnType(methodBuilder, returnType);
		}
	}
764450
private static <A extends Annotation> LinkedHashSet<String> extractFieldsFromAnnotation(final SQLiteModelMethod method, Class<A> annotationClazz, final boolean includePrimaryKey) {
		final SQLiteEntity entity = method.getEntity();

		List<String> annotatedFieldValues = AnnotationUtility.extractAsStringArray(method.getElement(), annotationClazz, AnnotationAttributeType.FIELDS);
		List<String> annotatedExcludedFieldValues = AnnotationUtility.extractAsStringArray(method.getElement(), annotationClazz, AnnotationAttributeType.EXCLUDED_FIELDS);
		CollectionUtils.trim(annotatedFieldValues);
		CollectionUtils.trim(annotatedExcludedFieldValues);

		final One<Integer> count = new One<>(0);

		// extract properties from managed bean
		final Set<String> allFields = new LinkedHashSet<>();
		forEachFields(method, new OnPropertyListener() {

			@Override
			public void onProperty(SQLProperty item) {
				if (!item.isPrimaryKey() || (item.isPrimaryKey() && includePrimaryKey)) {
					allFields.add(item.getName());
				}

				if (TypeUtility.isEquals(item.getPropertyType().getTypeName(), typeName(entity.getElement()))) {
					count.value0++;
				}
			}
		});

		// use attribute includedFields and excludedFields to mantain or remove
		// properties from selected set.
		if (annotatedFieldValues.size() == 0 && annotatedExcludedFieldValues.size() == 0) {
			// if no fields was selected, select all
			annotatedFieldValues.clear();
			annotatedFieldValues.addAll(allFields);
		} else if (annotatedExcludedFieldValues.size() > 0) {
			for (String fieldName : annotatedExcludedFieldValues) {
				if (!entity.contains(fieldName)) {
					AssertKripton.failUnknownPropertyInJQLException(method, annotationClazz, AnnotationAttributeType.EXCLUDED_FIELDS, fieldName);
				}
			}

			allFields.removeAll(annotatedExcludedFieldValues);

			annotatedFieldValues.clear();
			annotatedFieldValues.addAll(allFields);
		}
		LinkedHashSet<String> result = new LinkedHashSet<>();
		result.addAll(annotatedFieldValues);

		return result;
	}
222026
private void parseRelations(final Object originalEntity, final Object relationEntity,
            final Map<String, Object> relationsMap, final PersistenceDelegator pd, final EntityMetadata metadata,
            boolean lazilyloaded, Map<Object, Object> relationStack)
    {

        for (Relation relation : metadata.getRelations())
        {
            if (relation != null)
            {
                FetchType fetchType = relation.getFetchType();

                if (!lazilyloaded && fetchType.equals(FetchType.LAZY))
                {
                    final Object entityId = PropertyAccessorHelper.getId(relationEntity, metadata);
                    getAssociationBuilder().setProxyRelationObject(relationEntity, relationsMap, metadata, pd,
                            entityId, relation);
                }
                else
                {

                    if (relation.isUnary() && relation.getTargetEntity().isAssignableFrom(originalEntity.getClass()))
                    {
                        Object associationObject = PropertyAccessorHelper.getObject(relationEntity,
                                relation.getProperty());
                        if (relation.getType().equals(ForeignKey.ONE_TO_ONE))
                        {
                            if ((associationObject == null || ProxyHelper.isProxyOrCollection(associationObject)))
                            {
                                PropertyAccessorHelper.set(relationEntity, relation.getProperty(), originalEntity);
                            }
                        }
                        else if (relationsMap != null
                                && relationsMap.containsKey(relation.getJoinColumnName(kunderaMetadata)))
                        {
                            PropertyAccessorHelper.set(relationEntity, relation.getProperty(), originalEntity);
                        }
                    }
                    else
                    {
                        // Here
                        // onRelation(relationEntity, relationsMap, metadata,
                        // pd,
                        // relation, relationType);
                        final Object entityId = PropertyAccessorHelper.getId(relationEntity, metadata);
                        Object relationValue = relationsMap != null ? relationsMap.get(relation
                                .getJoinColumnName(kunderaMetadata)) : null;
                        final EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(
                                kunderaMetadata, relation.getTargetEntity());
                        List immediateRelations = fetchRelations(relation, metadata, pd, entityId, relationValue,
                                targetEntityMetadata);
                        // Here in case of one-to-many/many-to-one we should
                        // skip
                        // this
                        // relation as it
                        if (immediateRelations != null && !immediateRelations.isEmpty())
                        {
                            for (Object immediateRelation : immediateRelations)
                            {
                                if (immediateRelation != null )
                                {
                                    if (existsInRelationStack(relationStack, immediateRelation, targetEntityMetadata))
                                    {
                                        setRelationToEntity(
                                                relationEntity,
                                                fetchFromRelationStack(relationStack, immediateRelation,
                                                        targetEntityMetadata), relation);

                                    }
                                    else
                                    {
                                        addToRelationStack(relationStack, immediateRelation, targetEntityMetadata);
                                        onParseRelation(relationEntity, pd, targetEntityMetadata, immediateRelation,
                                                relation, lazilyloaded, relationStack);
                                      

                                    }
                                    PersistenceCacheManager.addEntityToPersistenceCache(getEntity(relationEntity), pd,
                                            PropertyAccessorHelper.getId(relationEntity, metadata));
                                }
                            }

                        }
                    }
                }
            }
        }
    }
171849
private JvmOperation getJvmOperation(IMethod method, JvmType context)
			throws JavaModelException {
		if (context instanceof JvmDeclaredType) {
			final JvmDeclaredType declaredType = (JvmDeclaredType) context;
			final ActionParameterTypes jdtSignature = this.actionPrototypeProvider.createParameterTypes(
					Flags.isVarargs(method.getFlags()),
					getFormalParameterProvider(method));
			for (final JvmOperation jvmOperation : declaredType.getDeclaredOperations()) {
				final ActionParameterTypes jvmSignature = this.actionPrototypeProvider.createParameterTypesFromJvmModel(
						jvmOperation.isVarArgs(),
						jvmOperation.getParameters());
				if (jvmSignature.equals(jdtSignature)) {
					return jvmOperation;
				}
			}
		}
		return null;
	}
1172567
private static String initFindRelationshipQuery(EntityKeyMetadata ownerEntityKeyMetadata, AssociationKeyMetadata associationKeyMetadata) {
		int offset = 0;
		StringBuilder queryBuilder = new StringBuilder( "MATCH " );
		queryBuilder.append( "(n:" );
		queryBuilder.append( ENTITY );
		queryBuilder.append( ":" );
		appendLabel( ownerEntityKeyMetadata, queryBuilder );
		appendProperties( ownerEntityKeyMetadata, queryBuilder );
		queryBuilder.append( ") - " );
		queryBuilder.append( "[r" );
		queryBuilder.append( ":" );
		appendRelationshipType( queryBuilder, associationKeyMetadata );
		offset = ownerEntityKeyMetadata.getColumnNames().length;
		if ( associationKeyMetadata.getRowKeyIndexColumnNames().length > 0 ) {
			appendProperties( queryBuilder, associationKeyMetadata.getRowKeyIndexColumnNames(), offset );
			queryBuilder.append( "] - (t" );
		}
		else {
			queryBuilder.append( "] - (t" );
			appendProperties( queryBuilder, associationKeyMetadata.getAssociatedEntityKeyMetadata().getEntityKeyMetadata().getColumnNames(), offset );
		}
		queryBuilder.append( ")" );
		queryBuilder.append( " RETURN r" );
		return queryBuilder.toString();
	}