Populate entity.

@param tr
the tr
@param m
the m
@param entity
the entity
@param relationNames
the relation names
@param isWrapReq
the is wrap req
@return the object
967504
public Object populateEntity(ThriftRow tr, EntityMetadata m, Object entity, List<String> relationNames,
            boolean isWrapReq)
    {
        Map<String, Object> relations = new HashMap<String, Object>();
        try
        {
            boolean isCql3Enabled = clientBase.isCql3Enabled(m);
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());
            EntityType entityType = metaModel.entity(m.getEntityClazz());

            for (Column column : tr.getColumns())
            {
                if (column != null)
                {
                    String thriftColumnName = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());
                    if ((CassandraConstants.CQL_KEY.equalsIgnoreCase(thriftColumnName) || ((AbstractAttribute) m
                            .getIdAttribute()).getJPAColumnName().equals(thriftColumnName)) && tr.getId() == null)
                    {
                        entity = KunderaCoreUtils.initialize(m, entity, null);
                        setId(m, entity, column.getValue(), isCql3Enabled);
                    }
                    else
                    {
                        entity = onColumn(column, m, entity, entityType, relationNames, isWrapReq, relations,
                                isCql3Enabled);

                        String discriminatorColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();
                        String discriminatorValue = ((AbstractManagedType) entityType).getDiscriminatorValue();

                        if (thriftColumnName != null
                                && thriftColumnName.equals(discriminatorColumn)
                                && column.getValue() != null
                                && !PropertyAccessorFactory.STRING.fromBytes(String.class, column.getValue()).equals(
                                        discriminatorValue))
                        {
                            entity = null;
                            break;
                        }
                    }
                }
            }

            // Add all super columns to entity
            Collection embeddedCollection = null;
            Field embeddedCollectionField = null;

            boolean mappingProcessed = false;
            Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();
            Map<String, Field> superColumnNameToFieldMap = new HashMap<String, Field>();

            for (SuperColumn superColumn : tr.getSuperColumns())
            {
                if (superColumn != null)
                {

                    entity = KunderaCoreUtils.initialize(m, entity, tr.getId());
                    String scName = PropertyAccessorFactory.STRING.fromBytes(String.class, superColumn.getName());
                    String scNamePrefix = null;

                    // Map to hold property-name=>foreign-entity relations
                    Map<String, Set<String>> foreignKeysMap = new HashMap<String, Set<String>>();

                    // Get a name->field map for super-columns
                    if (!mappingProcessed)
                    {
                        MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap,
                                superColumnNameToFieldMap, kunderaMetadata);
                        mappingProcessed = true;
                    }

                    if (scName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) != -1)
                    {
                        scNamePrefix = MetadataUtils.getEmbeddedCollectionPrefix(scName);
                        embeddedCollectionField = superColumnNameToFieldMap.get(scNamePrefix);

                        if (embeddedCollection == null)
                        {
                            embeddedCollection = MetadataUtils.getEmbeddedCollectionInstance(embeddedCollectionField);
                        }

                        Object embeddedObject = MetadataUtils.getEmbeddedGenericObjectInstance(embeddedCollectionField);

                        scrollOverSuperColumn(m, relationNames, isWrapReq, relations, entityType, superColumn,
                                embeddedObject, columnNameToFieldMap);

                        Collection collection = PropertyAccessorHelper.getCollectionInstance(embeddedCollectionField);
                        collection.add(embeddedObject);

                        PropertyAccessorHelper.set(entity, embeddedCollectionField, collection);

                        embeddedCollection.add(embeddedObject);

                        // Add this embedded object to cache
                        ElementCollectionCacheManager.getInstance().addElementCollectionCacheMapping(tr.getId(),
                                embeddedObject, scName);
                    }
                    else
                    {
                        if (superColumnNameToFieldMap.containsKey(scName))
                        {
                            Field field = superColumnNameToFieldMap.get(scName);

                            Object embeddedObj = PropertyAccessorHelper.getObject(entity, field);
                            if (embeddedObj == null)
                            {
                                embeddedObj = field.getType().newInstance();
                            }
                            // column
                            scrollOverSuperColumn(m, relationNames, isWrapReq, relations, entityType, superColumn,
                                    embeddedObj, columnNameToFieldMap);
                            PropertyAccessorHelper.set(entity, field, embeddedObj);
                        }
                        else
                        {
                            scrollOverSuperColumn(m, relationNames, isWrapReq, relations, entityType, superColumn,
                                    entity, isCql3Enabled);
                        }

                    }
                }
            }

            mappingProcessed = false;

            for (CounterColumn counterColumn : tr.getCounterColumns())
            {
                if (counterColumn != null)
                {
                    entity = KunderaCoreUtils.initialize(m, entity, tr.getId());
                    onCounterColumn(counterColumn, m, entity, entityType, relationNames, isWrapReq, relations,
                            isCql3Enabled);
                }
            }

            for (CounterSuperColumn counterSuperColumn : tr.getCounterSuperColumns())
            {
                if (counterSuperColumn != null)
                {
                    entity = KunderaCoreUtils.initialize(m, entity, tr.getId());
                    String scName = PropertyAccessorFactory.STRING
                            .fromBytes(String.class, counterSuperColumn.getName());
                    String scNamePrefix = null;

                    // Map to hold property-name=>foreign-entity relations
                    Map<String, Set<String>> foreignKeysMap = new HashMap<String, Set<String>>();

                    // Get a name->field map for super-columns
                    if (!mappingProcessed)
                    {
                        MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap,
                                superColumnNameToFieldMap, kunderaMetadata);
                        mappingProcessed = true;
                    }

                    if (scName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) != -1)
                    {
                        scNamePrefix = MetadataUtils.getEmbeddedCollectionPrefix(scName);
                        embeddedCollectionField = superColumnNameToFieldMap.get(scNamePrefix);

                        if (embeddedCollection == null)
                        {
                            embeddedCollection = MetadataUtils.getEmbeddedCollectionInstance(embeddedCollectionField);
                        }

                        Object embeddedObject = MetadataUtils.getEmbeddedGenericObjectInstance(embeddedCollectionField);

                        scrollOverCounterSuperColumn(m, relationNames, isWrapReq, relations, entityType,
                                counterSuperColumn, embeddedObject, columnNameToFieldMap);
                        embeddedCollection.add(embeddedObject);

                        // Add this embedded object to cache
                        ElementCollectionCacheManager.getInstance().addElementCollectionCacheMapping(tr.getId(),
                                embeddedObject, scName);
                    }
                    else
                    {
                        if (superColumnNameToFieldMap.containsKey(scName))
                        {
                            Field field = superColumnNameToFieldMap.get(scName);
                            Object embeddedObj = field.getType().newInstance();
                            // column
                            scrollOverCounterSuperColumn(m, relationNames, isWrapReq, relations, entityType,
                                    counterSuperColumn, embeddedObj, columnNameToFieldMap);
                            PropertyAccessorHelper.set(entity, field, embeddedObj);
                        }
                        else
                        {
                            scrollOverCounterSuperColumn(m, relationNames, isWrapReq, relations, entityType,
                                    counterSuperColumn, entity, isCql3Enabled);
                        }
                    }
                }
            }

            if (embeddedCollection != null && !embeddedCollection.isEmpty())
            {
                PropertyAccessorHelper.set(entity, embeddedCollectionField, embeddedCollection);
            }

        }
        catch (Exception e)
        {
            log.error("Eror while retrieving data, Caused by: .", e);
            throw new PersistenceException(e);
        }

        if (entity != null && tr.getId() != null)
        {
            PropertyAccessorHelper.setId(entity, m, tr.getId());
        }
        return isWrapReq && relations != null && !relations.isEmpty() ? new EnhanceEntity(entity,
                PropertyAccessorHelper.getId(entity, m), relations) : entity;
    }
71764
public List find(String nativeQuery, List<String> relations, EntityMetadata m)
    {
        List entities = new ArrayList();

        s = getStatelessSession();

        SQLQuery q = s.createSQLQuery(nativeQuery);
        q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);

        List result = q.list();

        try
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());

            EntityType entityType = metaModel.entity(m.getEntityClazz());

            List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();
            for (Object o : result)
            {
                Map<String, Object> relationValue = null;
                Object entity = null;
                EntityMetadata subEntityMetadata = null;
                if (!subManagedType.isEmpty())
                {
                    for (AbstractManagedType subEntity : subManagedType)
                    {
                        String discColumn = subEntity.getDiscriminatorColumn();
                        String disColValue = subEntity.getDiscriminatorValue();
                        Object value = ((Map<String, Object>) o).get(discColumn);
                        if (value != null && value.toString().equals(disColValue))
                        {
                            subEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                                    subEntity.getJavaType());
                            break;
                        }
                    }
                    entity = instantiateEntity(subEntityMetadata.getEntityClazz(), entity);
                    relationValue = HibernateUtils.getTranslatedObject(kunderaMetadata, entity,
                            (Map<String, Object>) o, m);

                }
                else
                {
                    entity = instantiateEntity(m.getEntityClazz(), entity);
                    relationValue = HibernateUtils.getTranslatedObject(kunderaMetadata, entity,
                            (Map<String, Object>) o, m);
                }

                if (relationValue != null && !relationValue.isEmpty())
                {
                    entity = new EnhanceEntity(entity, PropertyAccessorHelper.getId(entity, m), relationValue);
                }
                entities.add(entity);
            }
            return entities;
        }
        catch (Exception e)
        {
            if (e.getMessage().equals("Can not be translated into entity."))
            {
                return result;
            }
            throw new EntityReaderException(e);
        }
    }
493165
protected List<Object> populateEntities(EntityMetadata m, Client client)
    {
        if (log.isDebugEnabled())
        {
            log.debug("on start of fetching non associated entities");
        }
        List<Object> result = new ArrayList<Object>();

        initializeReader();

        try
        {
            if (MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
            {
                List<String> relations = new ArrayList<String>();
                if (kunderaQuery.isNative())
                {
                    return ((HibernateClient) client).find(getJPAQuery(), relations, m);

                }
                else
                {
                    return ((HibernateClient) client).findByQuery(getJPAQuery(), getParamaters(), firstResult, maxResult);

                }
            }
            else
            {
                return populateUsingLucene(m, client, result, null);
            }
        }
        catch (Exception e)
        {
            log.error("Error during query execution, Caused by: {}.", e);
            throw new QueryHandlerException(e);
        }
    }
478176
private void populateQueryComponents(EntityMetadata m, QueryComponent sq)
    {
        boolean hasChildren = false;
        if (sq.children != null && sq.children.size() > 0)
        {
            hasChildren = true;
            for (QueryComponent subQ : sq.children)
            {
                populateQueryComponents(m, subQ);
            }
        }
        if (sq.clauses.size() > 0 || hasChildren)
        {
            if (sq.clauses.size() > 0)
            {
                sq.actualQuery = createSubMongoQuery(m, sq.clauses);
            }
            if (hasChildren)
            {
                List<BasicDBObject> childQs = new ArrayList<BasicDBObject>();
                if (sq.clauses.size() > 0)
                    childQs.add(sq.actualQuery);
                for (QueryComponent subQ : sq.children)
                {
                    childQs.add(subQ.actualQuery);
                }
                if (childQs.size() == 1)
                {
                    sq.actualQuery = childQs.get(0);
                }
                else if (sq.isAnd)
                {
                    BasicDBObject dbo = new BasicDBObject("$and", childQs);
                    sq.actualQuery = dbo;
                }
                else
                {
                    BasicDBObject dbo = new BasicDBObject("$or", childQs);
                    sq.actualQuery = dbo;
                }
            }
        }
    }
463458
public List<Object> fromThriftRow(Class<?> clazz, EntityMetadata m, List<String> relationNames, boolean isWrapReq,
            ConsistencyLevel consistencyLevel, Object... rowIds) throws Exception
    {
        List<Object> entities = new ArrayList<Object>();
        if (rowIds != null)
        {
            for (Object rowKey : rowIds)
            {
                Object e = fromThriftRow(clazz, m, rowKey, relationNames, isWrapReq, consistencyLevel);
                if (e != null)
                {
                    entities.add(e);
                }
            }
        }
        return entities;
    }
769770
protected void computeEntityViaColumns(EntityMetadata m, boolean isRelation, List<String> relations,
        List<Object> entities, Map<ByteBuffer, List<Column>> qResults) {
        MetamodelImpl metaModel =
            (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());

        EntityType entityType = metaModel.entity(m.getEntityClazz());

        List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();

        for (ByteBuffer key : qResults.keySet()) {
            onColumn(m, isRelation, relations, entities, qResults.get(key), subManagedType, key);
        }
    }
602743
private void onParseRelation(Object entity, final PersistenceDelegator pd, EntityMetadata targetEntityMetadata,
            Object relationEntity, Relation relation, boolean lazilyloaded, Map<Object, Object> relationStack)
    {
        parseRelations(entity, getEntity(relationEntity), getPersistedRelations(relationEntity), pd,
                targetEntityMetadata, lazilyloaded, relationStack);

        // if relation ship is unary, no problem else we need to add
        setRelationToEntity(entity, relationEntity, relation);
    }
703078
private Object wrap(Map<String, Object> results, EntityType entityType, Object result, EntityMetadata metadata,
            boolean isIdSet)
    {

        Map<String, Object> relations = new HashMap<String, Object>();
        Object key = null;
        Set<Attribute> attributes = entityType.getAttributes();
        for (Attribute attribute : attributes)
        {
            String fieldName = ((AbstractAttribute) attribute).getJPAColumnName();

            if (!attribute.isAssociation())
            {
                Object fieldValue = results.get(fieldName);

                key = onId(key, attribute, fieldValue);

                if (!isIdSet && key != null)
                {
                    PropertyAccessorHelper.setId(result, metadata, key);
                }

                fieldValue = onEnum(attribute, fieldValue);

                // TODOO:This has to be corrected. Reason is, in case of execute
                // query over composite key. It will not work

                setField(result, key, attribute, fieldValue);
            }

            if (attribute.isAssociation())
            {
                Object fieldValue = results.get(fieldName);
                relations.put(fieldName, fieldValue);
            }
        }
        return relations.isEmpty() ? result : new EnhanceEntity(result, key, relations);
    }
1214120
static EntityManagerException wrap(DatastoreException exp) {
    switch (exp.getCode()) {
      case ERROR_CODE_ENTITY_NOT_FOUND:
        return new EntityNotFoundException(exp);
      case ERROR_CODE_ENTITY_ALREADY_EXISTS:
        return new EntityAlreadyExistsException(exp);
      default:
        return new EntityManagerException(exp);

    }
  }
567374
@Override
    protected List populateEntities(EntityMetadata m, Client client)
    {
        List results = new ArrayList();

        if (!MetadataUtils.useSecondryIndex(((ClientBase) client).getClientMetadata()))
        {
            results.addAll(populateUsingLucene(m, client, null, getKunderaQuery().getResult()));
        }

        else
        {
            MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    m.getPersistenceUnit());
            EntityType entityType = metaModel.entity(m.getEntityClazz());

            KuduClient kuduClient = ((KuduDBClient) client).getKuduClient();
            KuduTable table;
            try
            {
                table = kuduClient.openTable(m.getTableName());
            }
            catch (Exception e)
            {
                logger.error("Cannot open table : " + m.getTableName(), e);
                throw new KunderaException("Cannot open table : " + m.getTableName(), e);
            }

            KuduScannerBuilder scannerBuilder = kuduClient.newScannerBuilder(table);
            JPQLExpression jpqlExp = kunderaQuery.getJpqlExpression();
            List<String> selectColumns = KunderaQueryUtils.getSelectColumns(jpqlExp);
            if (!selectColumns.isEmpty())
            {
                // select by specific columns, set projection
                scannerBuilder.setProjectedColumnNames(selectColumns);
            }
            if (KunderaQueryUtils.hasWhereClause(jpqlExp))
            {
                // add predicate filters
                WhereClause whereClause = KunderaQueryUtils.getWhereClause(jpqlExp);
                Expression whereExp = whereClause.getConditionalExpression();
                parseAndBuildFilters(entityType, scannerBuilder, whereExp);
            }

            KuduScanner scanner = scannerBuilder.build();

            Object entity;
            while (scanner.hasMoreRows())
            {
                RowResultIterator rowResultIter;
                try
                {
                    rowResultIter = scanner.nextRows();
                }
                catch (Exception e)
                {
                    logger.error("Cannot get results from table : " + m.getTableName(), e);
                    throw new KunderaException("Cannot get results from table : " + m.getTableName(), e);
                }

                while (rowResultIter.hasNext())
                {
                    RowResult result = rowResultIter.next();
                    entity = KunderaCoreUtils.createNewInstance(m.getEntityClazz());
                    // populate RowResult to entity object and return
                    ((KuduDBClient) client).populateEntity(entity, result, entityType, metaModel);
                    results.add(entity);
                    logger.debug(result.rowToString());
                }
            }
        }
        return results;
    }
529298
public <E> E fromThriftRow(Class<E> clazz, EntityMetadata m, DataRow<SuperColumn> tr) throws Exception
    {

        // Instantiate a new instance
        E e = null;

        // Set row-key. Note:

        // Get a name->field map for super-columns
        Map<String, Field> columnNameToFieldMap = new HashMap<String, Field>();
        Map<String, Field> superColumnNameToFieldMap = new HashMap<String, Field>();
        MetadataUtils.populateColumnAndSuperColumnMaps(m, columnNameToFieldMap, superColumnNameToFieldMap,
                kunderaMetadata);

        Collection embeddedCollection = null;
        Field embeddedCollectionField = null;
        for (SuperColumn sc : tr.getColumns())
        {
            if (e == null)
            {
                // Instantiate a new instance
                e = clazz.newInstance();

                // Set row-key.
                PropertyAccessorHelper.setId(e, m, tr.getId());
            }

            String scName = PropertyAccessorFactory.STRING.fromBytes(String.class, sc.getName());
            String scNamePrefix = null;

            if (scName.indexOf(Constants.EMBEDDED_COLUMN_NAME_DELIMITER) != -1)
            {
                scNamePrefix = MetadataUtils.getEmbeddedCollectionPrefix(scName);
                embeddedCollectionField = superColumnNameToFieldMap.get(scNamePrefix);
                embeddedCollection = MetadataUtils.getEmbeddedCollectionInstance(embeddedCollectionField);
                Object embeddedObject = populateEmbeddedObject(sc, m);
                embeddedCollection.add(embeddedObject);
                PropertyAccessorHelper.set(e, embeddedCollectionField, embeddedCollection);
            }
            else
            {
                boolean intoRelations = false;
                if (scName.equals(Constants.FOREIGN_KEY_EMBEDDED_COLUMN_NAME))
                {
                    intoRelations = true;
                }

                for (Column column : sc.getColumns())
                {
                    if (column != null)
                    {
                        String name = PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());
                        byte[] value = column.getValue();

                        if (value == null)
                        {
                            continue;
                        }

                        if (intoRelations)
                        {
                            String foreignKeys = PropertyAccessorFactory.STRING.fromBytes(String.class, value);
                            Set<String> keys = MetadataUtils.deserializeKeys(foreignKeys);
                        }
                        else
                        {
                            // set value of the field in the bean
                            Field field = columnNameToFieldMap.get(name);
                            Object embeddedObject = PropertyAccessorHelper.getObject(e, scName);
                            PropertyAccessorHelper.set(embeddedObject, field, value);
                        }
                    }
                }
            }
        }

        if (log.isInfoEnabled())
        {
            log.info("Returning entity {} for class {}", e, clazz);
        }
        return e;
    }
1337868
public List executeQuery(String query, EntityMetadata m, KunderaQuery kunderaQuery)
    {
        DataFrame dataFrame = getDataFrame(query, m, kunderaQuery);

        // dataFrame.show();
        return dataHandler.loadDataAndPopulateResults(dataFrame, m, kunderaQuery);
    }
1069887
@Override
    protected List<Object> recursivelyPopulateEntities(EntityMetadata m, Client client)
    {
        List result = populateEntities(m, client);
        return setRelationEntities(result, client, m);
    }
755739
@Override
    protected List<Object> populateEntities(EntityMetadata m, Client client)
    {
        return onQuery(m, client);
    }
720769
protected void onColumn(EntityMetadata m, boolean isRelation, List<String> relations, List<Object> entities,
        List<Column> columns, List<AbstractManagedType> subManagedType, ByteBuffer key) {
        if (!columns.isEmpty()) {
            Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key.array());
            ThriftRow tr = new ThriftRow(id, m.getTableName(), columns, new ArrayList<SuperColumn>(0),
                new ArrayList<CounterColumn>(0), new ArrayList<CounterSuperColumn>(0));
            Object o = null;

            if (!subManagedType.isEmpty()) {
                for (AbstractManagedType subEntity : subManagedType) {
                    EntityMetadata subEntityMetadata =
                        KunderaMetadataManager.getEntityMetadata(kunderaMetadata, subEntity.getJavaType());

                    o = getDataHandler().populateEntity(tr, subEntityMetadata, KunderaCoreUtils.getEntity(o),
                        subEntityMetadata.getRelationNames(), isRelation);
                    if (o != null) {
                        break;
                    }
                }
            } else {
                o = getDataHandler().populateEntity(tr, m, KunderaCoreUtils.getEntity(o), relations, isRelation);
            }

            if (log.isInfoEnabled()) {
                log.info("Populating data for entity of clazz {} and row key {}.", m.getEntityClazz(), tr.getId());
            }

            if (o != null) {
                entities.add(o);
            }
        }
    }
758342
private <X> void populateRelationMetaData(EntityType entityType, Class<X> clazz, EntityMetadata metadata)
    {
        Set<Attribute> attributes = entityType.getAttributes();

        for (Attribute attribute : attributes)
        {
            if (attribute.isAssociation())
            {

                addRelationIntoMetadata(clazz, (Field) attribute.getJavaMember(), metadata);
            }
        }

    }
642703
private void populateCollectionFromJoinTable(Object entity, EntityMetadata entityMetadata,
            PersistenceDelegator delegator, Relation relation)
    {
        JoinTableMetadata jtMetadata = relation.getJoinTableMetadata();
        Client pClient = delegator.getClient(entityMetadata);

        String schema = entityMetadata.getSchema();

        EntityMetadata owningEntityMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
                relation.getTargetEntity());
        Class columnJavaType = owningEntityMetadata.getIdAttribute().getJavaType();
        if (jtMetadata == null)
        {
            columnJavaType = entityMetadata.getIdAttribute().getJavaType();
            Relation owningEntityMetadataRelation = owningEntityMetadata.getRelation(relation.getMappedBy());
            jtMetadata = owningEntityMetadataRelation.getJoinTableMetadata();
            pClient = delegator.getClient(owningEntityMetadata);
            schema = owningEntityMetadata.getSchema();
        }

        String joinTableName = jtMetadata.getJoinTableName();

        Set<String> joinColumns = jtMetadata.getJoinColumns();
        Set<String> inverseJoinColumns = jtMetadata.getInverseJoinColumns();

        String joinColumnName = (String) joinColumns.toArray()[0];
        String inverseJoinColumnName = (String) inverseJoinColumns.toArray()[0];

        Object entityId = PropertyAccessorHelper.getId(entity, entityMetadata);
        List<?> foreignKeys = pClient.getColumnsById(schema, joinTableName, joinColumnName, inverseJoinColumnName,
                entityId, columnJavaType);

        List childrenEntities = new ArrayList();

        if (foreignKeys != null)
        {
            for (Object foreignKey : foreignKeys)
            {
                EntityMetadata childMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
                        relation.getTargetEntity());

                Object child = delegator.find(relation.getTargetEntity(), foreignKey);
                Object obj = child instanceof EnhanceEntity && child != null ? ((EnhanceEntity) child).getEntity()
                        : child;

                // If child has any bidirectional relationship, process them
                // here
                Field biDirectionalField = relation.getBiDirectionalField();
                boolean isBidirectionalRelation = (biDirectionalField != null);

                if (isBidirectionalRelation && obj != null)
                {
                    Object columnValue = PropertyAccessorHelper.getId(obj, childMetadata);
                    Object[] pKeys = pClient.findIdsByColumn(entityMetadata.getSchema(), joinTableName, joinColumnName,
                            inverseJoinColumnName, columnValue, entityMetadata.getEntityClazz());
                    List parents = delegator.find(entity.getClass(), pKeys);
                    PropertyAccessorHelper.set(obj, biDirectionalField,
                            ObjectUtils.getFieldInstance(parents, biDirectionalField));
                    PersistenceCacheManager.addEntityToPersistenceCache(obj, delegator, columnValue);
                }

                childrenEntities.add(obj);
            }
        }
        Field childField = relation.getProperty();

        try
        {
            PropertyAccessorHelper.set(
                    entity,
                    childField,
                    PropertyAccessorHelper.isCollection(childField.getType()) ? ObjectUtils.getFieldInstance(
                            childrenEntities, childField) : childrenEntities.get(0));
            PersistenceCacheManager.addEntityToPersistenceCache(entity, delegator, entityId);
        }
        catch (PropertyAccessException ex)
        {
            throw new EntityReaderException(ex);
        }
    }