Search for primary key entity candidate field and retrieve its export field name
<p>
Primary key is field that (in that order):
- Have ID or UID name (case ignored)
- Is marked with enumerate gen annotation
- Randomly selected
559040
private String buildPrimaryKey(final IClassContainer container) {
        final Map<Field, FieldContainer> containerMap = container.getFormatSupported(Format.SQL);

        for (Map.Entry<Field, FieldContainer> entry : containerMap.entrySet()) {
            if (entry.getValue().isEnumerable()) {
                return entry.getValue().getExportName();
            } else if (entry.getKey().getName().equalsIgnoreCase("id")
                    || entry.getKey().getName().equalsIgnoreCase("uid")) {
                return entry.getValue().getExportName();
            }
        }

        return containerMap.entrySet().iterator().next().getValue().getExportName();
    }
496313
private void checkPrimaryKey(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException
    {
        if (CHECKLEVEL_NONE.equals(checkLevel))
        {
            return;
        }

        if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&
            classDef.getPrimaryKeys().isEmpty())
        {
            LogHelper.warn(true,
                           getClass(),
                           "checkPrimaryKey",
                           "The class "+classDef.getName()+" has no primary key");
        }
    }
1189381
private void checkAnnotationReference(Map<String, Candidate> candidatesMap, JAnnotatable annotatable) {
		for (JAnnotationUse annotation : annotatable.annotations()) {
			JAnnotationValue annotationMember = getAnnotationMember(annotation, "value");

			if (annotationMember instanceof JAnnotationArrayMember) {
				checkAnnotationReference(candidatesMap, (JAnnotationArrayMember) annotationMember);

				continue;
			}

			JExpression type = getAnnotationMemberExpression(annotation, "type");

			if (type == null) {
				// Can be the case for @XmlElement(name = "publication-reference", namespace = "http://mycompany.org/exchange")
				// or any other annotation without "type" 
				continue;
			}

			Candidate candidate = candidatesMap.get(generableToString(type).replace(".class", ""));

			if (candidate != null) {
				logger.debug("Candidate " + candidate.getClassName()
				            + " is used in XmlElements/XmlElementRef and hence won't be removed.");
				candidate.unmarkForRemoval();
			}
		}
	}
478646
private Object getEntityFieldValue(EntityMetadata entityMetadata, Object entity, String field)
    {
        Class clazz = entityMetadata.getEntityClazz();
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                entityMetadata.getPersistenceUnit());
        EntityType entityType = metaModel.entity(clazz);

        if (field.indexOf(".") > 0 && entityMetadata.getEntityClazz().equals(entity.getClass()))
        {
            String fieldName = field.substring(field.indexOf(".") + 1, field.length());
            Attribute attribute = entityType.getAttribute(fieldName);
            return PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());
        }
        else
        {
            // for hbase v2 client (sends arraylist for specific fields)
            if (entity instanceof ArrayList)
            {
                Object element = ((ArrayList) entity).get(0);
                ((ArrayList) entity).remove(0);
                return element;
            }
            else
            {
                return entity;
            }
        }
    }
534945
@Override
    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
        Object columnValue, Class entityClazz) {
        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);

        return getColumnsById(schemaName, tableName, columnName,
            ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName(), columnValue,
            metadata.getIdAttribute().getBindableJavaType()).toArray();
    }
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();
    }
371988
private void definePrimaryKey(ClassFile cf) {
        if (mPrimaryKey == null) {
            return;
        }

        // Add primary key annotation
        //
        // @PrimaryKey(value={"+/-propName", "+/-propName", ...})

        Annotation pk = cf.addRuntimeVisibleAnnotation(TypeDesc.forClass(PrimaryKey.class));

        Annotation.MemberValue[] props =
            new Annotation.MemberValue[mPrimaryKey.getPropertyCount()];
        pk.putMemberValue("value", props);
        int propPos = 0;
        Iterator<String> propNames = mPrimaryKey.getProperties();
        while (propNames.hasNext()) {
            String propName = propNames.next();
            props[propPos] = pk.makeMemberValue(propName);
            propPos++;
        }
    }
1178267
public static int getGeneratedKey(PreparedStatement statement) throws DatabaseException {
        ResultSet rs = null;
        int id = 0;
        try {
            rs = statement.getGeneratedKeys();
            if (!rs.next()) {
                throw new DatabaseException("Unable to get primary key for inserted row");
            }
            id = rs.getInt(1);
        } catch (SQLException ex) {
            throw new DatabaseException("Unable to get primary key for inserted row");
        } finally {
            closeResultSet(rs);
        }
        return id;
    }
839377
public String getPrimaryKeysString() {

        String result = "";

        for (int i = 0; i < primaryKeys.length; i++) {
            if (result != "") {
                result += ", ";
            }

            result += primaryKeys[i];
        }    // end of for (int i=0; i<primaryKeys.length; i++)

        return result;
    }
849043
private static org.hibernate.engine.spi.EntityKey getOptionalObjectKey(QueryParameters queryParameters, SharedSessionContractImplementor session) {
		final Object optionalObject = queryParameters.getOptionalObject();
		final Serializable optionalId = queryParameters.getOptionalId();
		final String optionalEntityName = queryParameters.getOptionalEntityName();

		if ( optionalObject != null && optionalEntityName != null ) {
			return session.generateEntityKey( optionalId, session.getEntityPersister( optionalEntityName, optionalObject ) );
		}
		else {
			return null;
		}
	}
1284269
private void fillPrimaryKeysBySequence(Object entity){
        if(!dialect.supportsGenerationType(GenerationType.SEQUENCE)){
            return;
        }

        BeanDesc beanDesc = beanDescFactory.getBeanDesc(entity.getClass());
        int size = beanDesc.getPropertyDescSize();

        for(int i=0; i < size; i++){
            PropertyDesc propertyDesc = beanDesc.getPropertyDesc(i);
            PrimaryKey primaryKey = propertyDesc.getAnnotation(PrimaryKey.class);

            if(primaryKey != null && primaryKey.generationType() == GenerationType.SEQUENCE){
                String sql = dialect.getSequenceSql(primaryKey.generator());
                Object value = sqlExecutor.getSingleResult(propertyDesc.getPropertyType(), sql, new Object[0]);
                propertyDesc.setValue(entity, value);
            }
        }
    }
630453
protected final String getValidJPAColumnName(Class<?> entity, Field f)
    {

        String name = null;

        if (f.isAnnotationPresent(Column.class))
        {
            Column c = f.getAnnotation(Column.class);
            if (!c.name().isEmpty())
            {
                name = c.name();
            }
            else
            {
                name = f.getName();
            }
        }
        else if (f.isAnnotationPresent(Basic.class))
        {
            name = f.getName();
        }

        if (f.isAnnotationPresent(Temporal.class))
        {
            if (!f.getType().equals(Date.class))
            {
                log.error("@Temporal must map to java.util.Date for @Entity(" + entity.getName() + "." + f.getName()
                        + ")");
                return name;
            }
            if (null == name)
            {
                name = f.getName();
            }
        }
        return name;
    }
650791
@Override
	public CPOption fetchByPrimaryKey(Serializable primaryKey) {
		Serializable serializable = entityCache.getResult(CPOptionModelImpl.ENTITY_CACHE_ENABLED,
				CPOptionImpl.class, primaryKey);

		if (serializable == nullModel) {
			return null;
		}

		CPOption cpOption = (CPOption)serializable;

		if (cpOption == null) {
			Session session = null;

			try {
				session = openSession();

				cpOption = (CPOption)session.get(CPOptionImpl.class, primaryKey);

				if (cpOption != null) {
					cacheResult(cpOption);
				}
				else {
					entityCache.putResult(CPOptionModelImpl.ENTITY_CACHE_ENABLED,
						CPOptionImpl.class, primaryKey, nullModel);
				}
			}
			catch (Exception e) {
				entityCache.removeResult(CPOptionModelImpl.ENTITY_CACHE_ENABLED,
					CPOptionImpl.class, primaryKey);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return cpOption;
	}
627138
private void processKeyField(Field field) {
    String fieldName = field.getName();
    Class<?> type = field.getType();
    if (!type.equals(DatastoreKey.class)) {
      String message = String.format("Invalid type, %s, for Key field %s in class %s. ", type,
          fieldName, entityClass);
      throw new EntityManagerException(message);
    }
    KeyMetadata keyMetadata = new KeyMetadata(field);
    entityMetadata.setKeyMetadata(keyMetadata);
  }
443583
public String getSqlQueryFromJPA(EntityMetadata entityMetadata, List<String> relations, Set<String> primaryKeys)
    {
        ApplicationMetadata appMetadata = kunderaMetadata.getApplicationMetadata();
        Metamodel metaModel = appMetadata.getMetamodel(entityMetadata.getPersistenceUnit());

        if (jpaQuery != null)
        {
            String query = appMetadata.getQuery(jpaQuery);
            boolean isNative = kunderaQuery != null ? kunderaQuery.isNative() : false;

            if (isNative)
            {
                return query != null ? query : jpaQuery;
            }
        }

        // Suffixing the UNDERSCORE instead of prefix as Oracle 11g complains
        // about invalid characters error while executing the request.
        String aliasName = entityMetadata.getTableName() + "_";

        StringBuilder queryBuilder = new StringBuilder("Select ");

        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());
        Set<Attribute> attributes = entityType.getAttributes();
        for (Attribute field : attributes)
        {
            if (!field.isAssociation() && !field.isCollection()
                    && !((Field) field.getJavaMember()).isAnnotationPresent(ManyToMany.class)
                    && !((Field) field.getJavaMember()).isAnnotationPresent(Transient.class)
                    && !((MetamodelImpl) metaModel).isEmbeddable(((AbstractAttribute) field).getBindableJavaType()))
            {
                queryBuilder.append(aliasName);
                queryBuilder.append(".");
                queryBuilder.append(((AbstractAttribute) field).getJPAColumnName());
                queryBuilder.append(", ");
            }
        }

        // Handle embedded columns, add them to list.
        Map<String, EmbeddableType> embeddedColumns = ((MetamodelImpl) metaModel).getEmbeddables(entityMetadata
                .getEntityClazz());
        for (EmbeddableType embeddedCol : embeddedColumns.values())
        {
            Set<Attribute> embeddedAttributes = embeddedCol.getAttributes();
            for (Attribute column : embeddedAttributes)
            {
                queryBuilder.append(aliasName);
                queryBuilder.append(".");
                queryBuilder.append(((AbstractAttribute) column).getJPAColumnName());
                queryBuilder.append(", ");
            }
        }

        if (relations != null)
        {
            for (String relation : relations)
            {
                Relation rel = entityMetadata.getRelation(entityMetadata.getFieldName(relation));
                String r = MetadataUtils.getMappedName(entityMetadata, rel, kunderaMetadata);
                if (!((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName().equalsIgnoreCase(
                        r != null ? r : relation)
                        && rel != null
                        && !rel.getProperty().isAnnotationPresent(ManyToMany.class)
                        && !rel.getProperty().isAnnotationPresent(OneToMany.class)
                        && (rel.getProperty().isAnnotationPresent(OneToOne.class)
                                && StringUtils.isBlank(rel.getMappedBy()) || rel.getProperty().isAnnotationPresent(
                                ManyToOne.class)))
                {
                    queryBuilder.append(aliasName);
                    queryBuilder.append(".");
                    queryBuilder.append(r != null ? r : relation);
                    queryBuilder.append(", ");
                }
            }
        }

        // Remove last ","
        queryBuilder.deleteCharAt(queryBuilder.lastIndexOf(","));

        queryBuilder.append(" From ");
        if (entityMetadata.getSchema() != null && !entityMetadata.getSchema().isEmpty())
        {
            queryBuilder.append(entityMetadata.getSchema() + ".");
        }
        queryBuilder.append(entityMetadata.getTableName());
        queryBuilder.append(" ");
        queryBuilder.append(aliasName);
        // add conditions
        if (filter != null)
        {
            queryBuilder.append(" Where ");
        }

        // Append conditions
        onCondition(entityMetadata, (MetamodelImpl) metaModel, primaryKeys, aliasName, queryBuilder, entityType);

        return queryBuilder.toString();
    }
634678
public FieldDescriptor[] getPkFields()
    {
        if (m_PkFieldDescriptors == null)
        {
            // 1. collect all Primary Key fields from Field list
            Vector vec = new Vector();
            // 1.a if descriptor describes an interface: take PK fields from an implementors ClassDescriptor
            if (m_isInterface)
            {
                if (getExtentClasses().size() == 0)
                {
                    throw new PersistenceBrokerException(
                        "No Implementors declared for interface "
                            + this.getClassOfObject().getName());
                }
                Class implementor = (Class) getExtentClasses().get(0);
                ClassDescriptor implCld = this.getRepository().getDescriptorFor(implementor);
                m_PkFieldDescriptors = implCld.getPkFields();
            }
            else
            {
                FieldDescriptor[] fields;
                // 1.b if not an interface The classdescriptor must have FieldDescriptors
                fields = getFieldDescriptions();
                // now collect all PK fields
                for (int i = 0; i < fields.length; i++)
                {
                    FieldDescriptor fd = fields[i];
                    if (fd.isPrimaryKey())
                    {
                        vec.add(fd);
                    }
                }
                // 2. Sort fields according to their getOrder() Property
                Collections.sort(vec, FieldDescriptor.getComparator());
                m_PkFieldDescriptors = (FieldDescriptor[]) vec.toArray(new FieldDescriptor[vec.size()]);
            }
        }
        return m_PkFieldDescriptors;
    }
956430
@Override
    public Object[] findIdsByColumn(String schemaName, String tableName, String pKeyName, String columnName,
            Object columnValue, Class entityClazz)
    {
        EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);

        byte[] valueInBytes = HBaseUtils.getBytes(columnValue);
        Filter f = new SingleColumnValueFilter(Bytes.toBytes(tableName), Bytes.toBytes(columnName), CompareOp.EQUAL,
                valueInBytes);
        KeyOnlyFilter keyFilter = new KeyOnlyFilter();
        FilterList filterList = new FilterList(f, keyFilter);
        try
        {
            return handler.scanRowyKeys(filterList, schemaName, tableName, columnName + "_" + columnValue, m
                    .getIdAttribute().getBindableJavaType());
        }
        catch (IOException e)
        {
            log.error("Error while executing findIdsByColumn(), Caused by: .", e);
            throw new KunderaException(e);
        }
    }