List of usage examples for javax.persistence.metamodel Attribute getName
String getName();
From source file:edu.kit.dama.mdm.core.jpa.MetaDataManagerJpa.java
@Override public final <T> List<T> find(final T first, final T last) throws UnauthorizedAccessAttemptException { List<T> resultList = new ArrayList(); boolean firstCondition = true; // Maybe one of the arguments could be null. // Test for the instance which is not null. T argumentNotNull = null;/* w w w .j av a2 s . co m*/ if (first != null) { argumentNotNull = first; } else if (last != null) { argumentNotNull = last; } if (argumentNotNull == null) { // both instances are null nothing to do. return resultList; } StringBuilder queryString = new StringBuilder("SELECT e FROM ") .append(EntityManagerHelper.getEntityTableName(argumentNotNull.getClass())).append(" e"); try { Metamodel metamodel = entityManager.getMetamodel(); for (Object attribute : metamodel.entity(argumentNotNull.getClass()).getAttributes()) { Attribute myAttribute = ((Attribute) attribute); LOGGER.trace("Attribute: {}\nName: {}\n ", attribute, myAttribute.getName()); // Only basic types where tested. if (myAttribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.BASIC) { String propertyName = myAttribute.getName(); String firstValue = null; String lastValue = null; if (first != null) { firstValue = BeanUtils.getProperty(first, propertyName); } if (last != null) { lastValue = BeanUtils.getProperty(last, propertyName); } if ((firstValue != null) || (lastValue != null)) { LOGGER.trace("At least one property is set!"); if (!firstCondition) { queryString.append(" AND "); } else { queryString.append(" WHERE"); firstCondition = false; } queryString.append(" e.").append(propertyName); if ((firstValue != null) && (lastValue != null)) { queryString.append(" BETWEEN '").append(firstValue).append("' AND '").append(lastValue) .append("'"); } else if (firstValue != null) { queryString.append(" >= '").append(firstValue).append("'"); } else { // lastValue != null queryString.append(" <= '").append(lastValue).append("'"); } } } else { LOGGER.trace( "****************************************" + "*****************************\nAttribute skipped: {}", myAttribute.getDeclaringType().getClass()); } } LOGGER.debug(queryString.toString()); Query q = entityManager.createQuery(queryString.toString()); applyProperties(q); resultList = (List<T>) q.getResultList(); } catch (Exception e) { LOGGER.warn("Failed to obtain result in find-method for query: " + queryString.toString(), e); } finally { finalizeEntityManagerAccess("find(first,last)", null, argumentNotNull); } return resultList; }
From source file:com.impetus.client.neo4j.GraphEntityMapper.java
/** * //from w w w . j a v a2s. c o m * Gets (if available) or creates a node for the given entity */ private Node getOrCreateNodeWithUniqueFactory(final Object entity, final Object id, final EntityMetadata m, GraphDatabaseService graphDb) { final String idColumnName = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName(); final MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(m.getPersistenceUnit()); final String idUniqueValue = serializeIdAttributeValue(m, metaModel, id); UniqueFactory<Node> factory = new UniqueFactory.UniqueNodeFactory(graphDb, m.getIndexName()) { /** * Initialize ID attribute */ @Override protected void initialize(Node created, Map<String, Object> properties) { // Set Embeddable ID attribute if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())) { // Populate embedded field value in serialized format created.setProperty(idColumnName, idUniqueValue); // Populated all other attributes of embedded into this node Set<Attribute> embeddableAttributes = metaModel .embeddable(m.getIdAttribute().getBindableJavaType()).getSingularAttributes(); for (Attribute attribute : embeddableAttributes) { String columnName = ((AbstractAttribute) attribute).getJPAColumnName(); if (columnName == null) columnName = attribute.getName(); Object value = PropertyAccessorHelper.getObject(id, (Field) attribute.getJavaMember()); if (value != null) created.setProperty(columnName, value); } } else { created.setProperty(idColumnName, properties.get(idColumnName)); } } }; if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())) { return factory.getOrCreate(idColumnName, idUniqueValue); } else { return factory.getOrCreate(idColumnName, id); } }
From source file:com.impetus.client.neo4j.GraphEntityMapper.java
/** * Populates a {@link Relationship} with attributes of a given relationship * entity object <code>relationshipObj</code> * //from ww w.ja v a2 s . c om * @param entityMetadata * @param targetNodeMetadata * @param relationship * @param relationshipObj */ public void populateRelationshipProperties(EntityMetadata entityMetadata, EntityMetadata targetNodeMetadata, Relationship relationship, Object relationshipObj) { MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(entityMetadata.getPersistenceUnit()); EntityType entityType = metaModel.entity(relationshipObj.getClass()); Set<Attribute> attributes = entityType.getSingularAttributes(); for (Attribute attribute : attributes) { Field f = (Field) attribute.getJavaMember(); if (!f.getType().equals(entityMetadata.getEntityClazz()) && !f.getType().equals(targetNodeMetadata.getEntityClazz())) { EntityMetadata relMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, relationshipObj.getClass()); String columnName = ((AbstractAttribute) attribute).getJPAColumnName(); if (metaModel.isEmbeddable(relMetadata.getIdAttribute().getBindableJavaType()) && ((SingularAttribute) attribute).isId()) { // Populate Embedded attribute value into relationship Object id = PropertyAccessorHelper.getId(relationshipObj, relMetadata); Object serializedIdValue = serializeIdAttributeValue(relMetadata, metaModel, id); relationship.setProperty(columnName, serializedIdValue); // Populate attributes of embedded fields into relationship Set<Attribute> embeddableAttributes = metaModel .embeddable(relMetadata.getIdAttribute().getBindableJavaType()).getSingularAttributes(); for (Attribute embeddableAttribute : embeddableAttributes) { String embeddedColumn = ((AbstractAttribute) embeddableAttribute).getJPAColumnName(); if (embeddedColumn == null) embeddedColumn = embeddableAttribute.getName(); Object value = PropertyAccessorHelper.getObject(id, (Field) embeddableAttribute.getJavaMember()); if (value != null) relationship.setProperty(embeddedColumn, value); } } else { Object value = PropertyAccessorHelper.getObject(relationshipObj, f); relationship.setProperty(columnName, toNeo4JProperty(value)); } } } }
From source file:org.jdal.dao.jpa.JpaDao.java
/** * Null References on one to many and one to one associations. * Will only work if association has annotated with a mappedBy attribute. * /*from w ww . j a v a 2 s. co m*/ * @param entity entity */ private void nullReferences(T entity) { EntityType<T> type = em.getMetamodel().entity(getEntityClass()); if (log.isDebugEnabled()) log.debug("Null references on entity " + type.getName()); for (Attribute<?, ?> a : type.getAttributes()) { if (PersistentAttributeType.ONE_TO_MANY == a.getPersistentAttributeType() || PersistentAttributeType.ONE_TO_ONE == a.getPersistentAttributeType()) { Object association = PropertyAccessorFactory.forDirectFieldAccess(entity) .getPropertyValue(a.getName()); if (association != null) { EntityType<?> associationType = null; if (a.isCollection()) { associationType = em.getMetamodel() .entity(((PluralAttribute<?, ?, ?>) a).getBindableJavaType()); } else { associationType = em.getMetamodel().entity(a.getJavaType()); } String mappedBy = JpaUtils.getMappedBy(a); if (mappedBy != null) { Attribute<?, ?> aa = associationType.getAttribute(mappedBy); if (PersistentAttributeType.MANY_TO_ONE == aa.getPersistentAttributeType()) { if (log.isDebugEnabled()) { log.debug("Null ManyToOne reference on " + associationType.getName() + "." + aa.getName()); } for (Object o : (Collection<?>) association) { PropertyAccessorFactory.forDirectFieldAccess(o).setPropertyValue(aa.getName(), null); } } else if (PersistentAttributeType.ONE_TO_ONE == aa.getPersistentAttributeType()) { if (log.isDebugEnabled()) { log.debug("Null OneToOne reference on " + associationType.getName() + "." + aa.getName()); } PropertyAccessorFactory.forDirectFieldAccess(association).setPropertyValue(aa.getName(), null); } } } } } }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java
private void handleBasicOrEmbedded(Object bean, ItemDelta delta, Attribute attribute) { Class outputType = getRealOutputType(attribute); PrismValue anyPrismValue = delta.getAnyValue(); Object value;//from ww w . j av a2s .c o m if (delta.isDelete() || (delta.isReplace() && (anyPrismValue == null || anyPrismValue.isEmpty()))) { value = null; } else { value = anyPrismValue.getRealValue(); } value = prismEntityMapper.map(value, outputType); try { PropertyUtils.setSimpleProperty(bean, attribute.getName(), value); } catch (Exception ex) { throw new SystemException("Couldn't set simple property for '" + attribute.getName() + "'", ex); } }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java
/** * modify// www .j ava2 s .co m */ public <T extends ObjectType> RObject<T> modifyObject(Class<T> type, String oid, Collection<? extends ItemDelta> modifications, PrismObject<T> prismObject, Session session) throws SchemaException { LOGGER.trace("Starting to build entity changes for {}, {}, \n{}", type, oid, DebugUtil.debugDumpLazily(modifications)); // normalize reference.relation qnames like it's done here ObjectTypeUtil.normalizeAllRelations(prismObject); // how to generate identifiers correctly now? to repo entities and to full xml, ids in full XML are generated // on different place than we later create new containers...how to match them // set proper owner/ownerOid/ownerType for containers/references/result and others // todo implement transformation from prism to entity (PrismEntityMapper), probably ROperationResult missing // validate lookup tables and certification campaigns // mark newly added containers/references as transient // validate metadata/*, assignment/metadata/*, assignment/construction/resourceRef changes PrismIdentifierGenerator<T> idGenerator = new PrismIdentifierGenerator<>( PrismIdentifierGenerator.Operation.MODIFY); idGenerator.collectUsedIds(prismObject); // preprocess modifications Collection<? extends ItemDelta> processedModifications = prismObject .narrowModifications((Collection<? extends ItemDelta<?, ?>>) modifications); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Narrowed modifications:\n{}", DebugUtil.debugDumpLazily(modifications)); } // process only real modifications Class<? extends RObject> objectClass = RObjectType.getByJaxbType(type).getClazz(); RObject<T> object = session.byId(objectClass).getReference(oid); ManagedType mainEntityType = entityRegistry.getJaxbMapping(type); for (ItemDelta delta : processedModifications) { ItemPath path = delta.getPath(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Processing delta with path '{}'", path); } if (isObjectExtensionDelta(path) || isShadowAttributesDelta(path)) { if (delta.getPath().size() == 1) { handleObjectExtensionWholeContainer(object, delta, idGenerator); } else { handleObjectExtensionOrAttributesDelta(object, delta, idGenerator); } continue; } AttributeStep attributeStep = new AttributeStep(); attributeStep.managedType = mainEntityType; attributeStep.bean = object; Iterator<ItemPathSegment> segments = path.getSegments().iterator(); while (segments.hasNext()) { ItemPathSegment segment = segments.next(); if (!(segment instanceof NameItemPathSegment)) { throw new SystemException("Segment '" + segment + "' in '" + path + "' is not a name item"); } NameItemPathSegment nameSegment = (NameItemPathSegment) segment; String nameLocalPart = nameSegment.getName().getLocalPart(); if (isAssignmentExtensionDelta(attributeStep, nameSegment)) { NameItemPathSegment lastNamed = delta.getPath().namedSegmentsOnly().lastNamed(); if (AssignmentType.F_EXTENSION.equals(lastNamed.getName())) { handleAssignmentExtensionWholeContainer((RAssignment) attributeStep.bean, delta, idGenerator); } else { handleAssignmentExtensionDelta((RAssignment) attributeStep.bean, delta, idGenerator); } continue; } if (isOperationResult(delta)) { handleOperationResult(attributeStep.bean, delta); continue; } if (isMetadata(delta)) { handleMetadata(attributeStep.bean, delta); } if (isFocusPhoto(delta)) { handlePhoto(attributeStep.bean, delta); continue; } Attribute attribute = findAttribute(attributeStep, nameLocalPart, path, segments, nameSegment); if (attribute == null) { // there's no table/column that needs update break; } if (segments.hasNext()) { attributeStep = stepThroughAttribute(attribute, attributeStep, segments); continue; } handleAttribute(attribute, attributeStep.bean, delta, prismObject, idGenerator); if ("name".equals(attribute.getName()) && RObject.class.isAssignableFrom(attribute.getDeclaringType().getJavaType())) { // we also need to handle "nameCopy" column, we doesn't need path/segments/nameSegment for this call Attribute nameCopyAttribute = findAttribute(attributeStep, "nameCopy", null, null, null); handleAttribute(nameCopyAttribute, attributeStep.bean, delta, prismObject, idGenerator); } } } handleObjectCommonAttributes(type, processedModifications, prismObject, object, idGenerator); LOGGER.trace("Entity changes applied"); return object; }
From source file:com.impetus.client.oraclenosql.OracleNoSQLClient.java
/** * Scroll and populate.//from w w w . j av a 2 s. c o m * * @param key * the key * @param entityMetadata * the entity metadata * @param metaModel * the meta model * @param schemaTable * the schema table * @param rowsIter * the rows iter * @param relationMap * the relation map * @param columnsToSelect * the columns to select * @return the list * @throws InstantiationException * the instantiation exception * @throws IllegalAccessException * the illegal access exception */ private List scrollAndPopulate(Object key, EntityMetadata entityMetadata, MetamodelImpl metaModel, Table schemaTable, Iterator<Row> rowsIter, Map<String, Object> relationMap, List<String> columnsToSelect) throws InstantiationException, IllegalAccessException { List results = new ArrayList(); Object entity = null; EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz()); // here while (rowsIter.hasNext()) { relationMap = new HashMap<String, Object>(); entity = initializeEntity(key, entityMetadata); Row row = rowsIter.next(); List<String> fields = row.getTable().getFields(); FieldDef fieldMetadata = null; FieldValue value = null; String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName(); if (/* eligibleToFetch(columnsToSelect, idColumnName) && */!metaModel .isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())) { populateId(entityMetadata, schemaTable, entity, row); } else { onEmbeddableId(entityMetadata, metaModel, schemaTable, entity, row); } Iterator<String> fieldIter = fields.iterator(); Set<Attribute> attributes = entityType.getAttributes(); for (Attribute attribute : attributes) { String jpaColumnName = ((AbstractAttribute) attribute).getJPAColumnName(); if (eligibleToFetch(columnsToSelect, jpaColumnName) && !attribute.getName().equals(entityMetadata.getIdAttribute().getName())) { if (metaModel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) { // readEmbeddable(value, columnsToSelect, // entityMetadata, metaModel, schemaTable, value, // attribute); EmbeddableType embeddableId = metaModel .embeddable(((AbstractAttribute) attribute).getBindableJavaType()); Set<Attribute> embeddedAttributes = embeddableId.getAttributes(); Object embeddedObject = ((AbstractAttribute) attribute).getBindableJavaType().newInstance(); for (Attribute embeddedAttrib : embeddedAttributes) { String embeddedColumnName = ((AbstractAttribute) embeddedAttrib).getJPAColumnName(); fieldMetadata = schemaTable.getField(embeddedColumnName); value = row.get(embeddedColumnName); NoSqlDBUtils.get(fieldMetadata, value, embeddedObject, (Field) embeddedAttrib.getJavaMember()); } PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), embeddedObject); } else { fieldMetadata = schemaTable.getField(jpaColumnName); value = row.get(jpaColumnName); if (!attribute.isAssociation() && value != null) { NoSqlDBUtils.get(fieldMetadata, value, entity, (Field) attribute.getJavaMember()); } else if (attribute.isAssociation() && value != null) { Relation relation = entityMetadata.getRelation(attribute.getName()); if (relation != null) { EntityMetadata associationMetadata = KunderaMetadataManager .getEntityMetadata(kunderaMetadata, relation.getTargetEntity()); if (!relation.getType().equals(ForeignKey.MANY_TO_MANY)) { relationMap.put(jpaColumnName, NoSqlDBUtils.get(fieldMetadata, value, (Field) associationMetadata.getIdAttribute().getJavaMember())); } } } } } } if (entity != null) { results.add(relationMap.isEmpty() ? entity : new EnhanceEntity(entity, key != null ? key : PropertyAccessorHelper.getId(entity, entityMetadata), relationMap)); } } return results; }
From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java
private AttributeStep stepThroughAttribute(Attribute attribute, AttributeStep step, Iterator<ItemPathSegment> segments) { Method method = (Method) attribute.getJavaMember(); switch (attribute.getPersistentAttributeType()) { case EMBEDDED: step.managedType = entityRegistry.getMapping(attribute.getJavaType()); Object child = invoke(step.bean, method); if (child == null) { // embedded entity doesn't exist we have to create it first, so it can be populated later Class childType = getRealOutputType(attribute); try { child = childType.newInstance(); PropertyUtils.setSimpleProperty(step.bean, attribute.getName(), child); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { throw new SystemException("Couldn't create new instance of '" + childType.getName() + "', attribute '" + attribute.getName() + "'", ex); }//from w ww. j av a 2 s .c om } step.bean = child; break; case ONE_TO_MANY: // object extension is handled separately, only {@link Container} and references are handled here Class clazz = getRealOutputType(attribute); IdItemPathSegment id = (IdItemPathSegment) segments.next(); Collection c = (Collection) invoke(step.bean, method); if (!Container.class.isAssignableFrom(clazz)) { throw new SystemException( "Don't know how to go through collection of '" + getRealOutputType(attribute) + "'"); } boolean found = false; for (Container o : (Collection<Container>) c) { long l = o.getId().longValue(); if (l == id.getId()) { step.managedType = entityRegistry.getMapping(clazz); step.bean = o; found = true; break; } } if (!found) { throw new RuntimeException("Couldn't find container of type '" + getRealOutputType(attribute) + "' with id '" + id + "'"); } break; case ONE_TO_ONE: // assignment extension is handled separately break; default: // nothing to do for other cases } return step; }
From source file:com.impetus.kundera.metadata.MetadataUtils.java
/** * Gets the enclosing document name.// w w w. java 2 s . c o m * * @param m * the m * @param criteria * Input criteria * @param viaColumnName * true if <code>criteria</code> is column Name, false if * <code>criteria</code> is column field name * @return the enclosing document name */ public static String getEnclosingEmbeddedFieldName(EntityMetadata m, String criteria, boolean viaColumnName, final KunderaMetadata kunderaMetadata) { String enclosingEmbeddedFieldName = null; StringTokenizer strToken = new StringTokenizer(criteria, "."); String embeddableAttributeName = null; String embeddedFieldName = null; String nestedEmbeddedFieldName = null; if (strToken.countTokens() > 0) { embeddableAttributeName = strToken.nextToken(); } if (strToken.countTokens() > 0) { embeddedFieldName = strToken.nextToken(); } if (strToken.countTokens() > 0) { nestedEmbeddedFieldName = strToken.nextToken(); } Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit()); EntityType entity = metaModel.entity(m.getEntityClazz()); try { Attribute attribute = entity.getAttribute(embeddableAttributeName); if (((MetamodelImpl) metaModel).isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) { EmbeddableType embeddable = metaModel .embeddable(((AbstractAttribute) attribute).getBindableJavaType()); Iterator<Attribute> attributeIter = embeddable.getAttributes().iterator(); while (attributeIter.hasNext()) { AbstractAttribute attrib = (AbstractAttribute) attributeIter.next(); if (viaColumnName && attrib.getName().equals(embeddedFieldName)) { if (nestedEmbeddedFieldName != null && ((MetamodelImpl) metaModel) .isEmbeddable(((AbstractAttribute) attrib).getBindableJavaType())) { EmbeddableType nestedEmbeddable = metaModel .embeddable(((AbstractAttribute) attrib).getBindableJavaType()); Iterator<Attribute> iter = embeddable.getAttributes().iterator(); while (iter.hasNext()) { AbstractAttribute nestedAttribute = (AbstractAttribute) iter.next(); if (viaColumnName && nestedAttribute.getName().equals(embeddedFieldName)) { return nestedAttribute.getName(); } if (!viaColumnName && nestedAttribute.getJPAColumnName().equals(embeddedFieldName)) { return nestedAttribute.getName(); } } } else if (nestedEmbeddedFieldName != null && !((MetamodelImpl) metaModel) .isEmbeddable(((AbstractAttribute) attrib).getBindableJavaType())) { return null; } else { return attribute.getName(); } } if (!viaColumnName && attrib.getJPAColumnName().equals(embeddedFieldName)) { return attribute.getName(); } } } } catch (IllegalArgumentException iax) { return null; } return enclosingEmbeddedFieldName; }
From source file:com.impetus.client.redis.RedisClient.java
/** * Wraps entity attributes into redis format byte[]. * /*from w ww . ja v a 2s . c o m*/ * @param entityMetadata * the entity metadata * @param wrapper * the wrapper * @param embeddedObject * the embedded object * @param attrib * the attrib * @param embeddedAttrib * the embedded attrib */ private void addToWrapper(EntityMetadata entityMetadata, AttributeWrapper wrapper, Object embeddedObject, Attribute attrib, Attribute embeddedAttrib) { byte[] value = PropertyAccessorHelper.get(embeddedObject, (Field) attrib.getJavaMember()); byte[] name; if (value != null) { if (embeddedAttrib == null) { name = getEncodedBytes(((AbstractAttribute) attrib).getJPAColumnName()); } else { name = getEncodedBytes( getHashKey(embeddedAttrib.getName(), ((AbstractAttribute) attrib).getJPAColumnName())); } // add column name as key and value as value wrapper.addColumn(name, value); // // {tablename:columnname,hashcode} for value // selective indexing. if (entityMetadata.getIndexProperties().containsKey(((AbstractAttribute) attrib).getJPAColumnName())) { String valueAsStr = PropertyAccessorHelper.getString(embeddedObject, (Field) attrib.getJavaMember()); wrapper.addIndex( getHashKey(entityMetadata.getTableName(), ((AbstractAttribute) attrib).getJPAColumnName()), getDouble(valueAsStr)); wrapper.addIndex( getHashKey(entityMetadata.getTableName(), getHashKey(((AbstractAttribute) attrib).getJPAColumnName(), valueAsStr)), getDouble(valueAsStr)); } } }