public static String getForeignKeyField(
     MasterDataMetaVO mdmetavo, String foreignEntityName, boolean withId) {
   final String foreignKeyField;
   final Set<String> foreignKeyFields = new TreeSet<String>();
   for (MasterDataMetaFieldVO field : mdmetavo.getFields()) {
     if (foreignEntityName.equals(field.getForeignEntity())) {
       foreignKeyFields.add(field.getFieldName());
     }
   }
   switch (foreignKeyFields.size()) {
     case 0:
       foreignKeyField = ModuleConstants.DEFAULT_FOREIGNKEYFIELDNAME;
       break;
     case 1:
       foreignKeyField = foreignKeyFields.iterator().next();
       break;
     default:
       // more than one...
       if (foreignKeyFields.contains(ModuleConstants.DEFAULT_FOREIGNKEYFIELDNAME)) {
         foreignKeyField = ModuleConstants.DEFAULT_FOREIGNKEYFIELDNAME;
       } else {
         foreignKeyField = foreignKeyFields.iterator().next();
       }
   }
   if (withId) {
     return foreignKeyField + "Id";
   } else {
     return foreignKeyField;
   }
 }
  /**
   * sets the parent id of masterdata records.
   *
   * @param iGenericObjectId
   */
  @Override
  public void setParent(
      String moduleEntityName,
      Integer iGenericObjectId,
      Map<EntityAndFieldName, String> collSubEntities) {
    if (iGenericObjectId == null) {
      throw new NullArgumentException("iGenericObjectId");
    }

    Long longId = IdUtils.toLongId(iGenericObjectId);
    /** @todo eliminate this workaround: */
    final MasterDataMetaProvider cache =
        SpringApplicationContextHolder.getBean(MasterDataMetaProvider.class);
    for (String sEntityName : this.getEntityNames()) {
      if (cache != null) {
        final MasterDataMetaVO mdmetavo = cache.getMetaData(sEntityName);
        if (mdmetavo.isEditable()) {
          for (EntityObjectVO mdvo : this.getData(sEntityName)) {
            String foreignKeyIdField = null;
            for (EntityAndFieldName entityAndFieldName : collSubEntities.keySet()) {
              if (entityAndFieldName.getEntityName().equals(sEntityName)) {
                foreignKeyIdField = entityAndFieldName.getFieldName();
                break;
              }
            }
            if (foreignKeyIdField == null)
              foreignKeyIdField = getForeignKeyField(mdmetavo, moduleEntityName, false);
            final Long iOldGenericObjectId = mdvo.getFieldId(foreignKeyIdField);
            if (iOldGenericObjectId != null && !longId.equals(iOldGenericObjectId)) {
              log.warn(
                  "Bad parent id in dependant masterdata record; old id: "
                      + iOldGenericObjectId
                      + ", new id: "
                      + longId
                      + ".");
            }
            if (iOldGenericObjectId == null
                || (!longId.equals(iOldGenericObjectId) && mdvo.isFlagUpdated())) {
              mdvo.getFieldIds().put(foreignKeyIdField, longId);
            }
          }
        }
      }
    }
  }