Example usage for javax.persistence.metamodel Attribute getDeclaringType

List of usage examples for javax.persistence.metamodel Attribute getDeclaringType

Introduction

In this page you can find the example usage for javax.persistence.metamodel Attribute getDeclaringType.

Prototype

ManagedType<X> getDeclaringType();

Source Link

Document

Return the managed type representing the type in which the attribute was declared.

Usage

From source file:com.github.gekoh.yagen.util.MappingUtils.java

private static void fillTreeEntityMap(Map<Class, TreeEntity> treeEntities, Set<Attribute> attributes,
        Class entityClass) {/*from   w w  w  .j a va  2 s . c om*/
    for (Attribute attribute : attributes) {
        if (attribute instanceof SingularAttribute
                && ((SingularAttribute) attribute).getType() instanceof EmbeddableType) {
            fillTreeEntityMap(treeEntities,
                    ((EmbeddableType) ((SingularAttribute) attribute).getType()).getAttributes(), entityClass);
        } else if (!attribute.isCollection()
                && attribute.getPersistentAttributeType() != Attribute.PersistentAttributeType.BASIC
                && attribute.getDeclaringType() instanceof EntityType) {
            Class targetEntity = attribute.getJavaType();
            addMasterEntity(treeEntities, entityClass, targetEntity);
        } else if (attribute.isCollection()
                && attribute.getPersistentAttributeType() != Attribute.PersistentAttributeType.MANY_TO_MANY
                && attribute instanceof PluralAttribute) {
            addMasterEntity(treeEntities, ((PluralAttribute) attribute).getElementType().getJavaType(),
                    entityClass);
        }
    }
    if (!entityClass.isAnnotationPresent(Table.class)) {
        Class lastEntity = entityClass;
        Class parent = lastEntity;
        do {
            parent = parent.getSuperclass();
            if (parent.isAnnotationPresent(Entity.class)) {
                addMasterEntity(treeEntities, parent, lastEntity);
                lastEntity = parent;
            }
            if (parent.isAnnotationPresent(Table.class)) {
                break;
            }
        } while (parent.getSuperclass() != null);
    }
}

From source file:com.github.gekoh.yagen.util.MappingUtils.java

private static void appendNonCollectionReferences(Set<Attribute> attributes, Map<String, Field> fields,
        String context) {//from www . ja v  a2 s.com
    for (Attribute attribute : attributes) {
        String attributeName = context + attribute.getName();

        if (attribute instanceof SingularAttribute
                && ((SingularAttribute) attribute).getType() instanceof EmbeddableType) {
            appendNonCollectionReferences(
                    ((EmbeddableType) ((SingularAttribute) attribute).getType()).getAttributes(), fields,
                    attributeName + ".");
        } else if (!attribute.isCollection()
                && attribute.getPersistentAttributeType() != Attribute.PersistentAttributeType.BASIC
                && attribute.getDeclaringType() instanceof EntityType) {
            fields.put(attributeName, (Field) attribute.getJavaMember());
        }
    }
}

From source file:com.jaxio.jpa.querybyexample.JpaUtil.java

public void verifyPath(List<Attribute<?, ?>> path) {
    List<Attribute<?, ?>> attributes = newArrayList(path);
    Class<?> from = null;//from   w  w w  . j  a v a 2 s .c o  m
    if (attributes.get(0).isCollection()) {
        from = ((PluralAttribute) attributes.get(0)).getElementType().getJavaType();
    } else {
        from = attributes.get(0).getJavaType();
    }
    attributes.remove(0);
    for (Attribute<?, ?> attribute : attributes) {
        if (!attribute.getDeclaringType().getJavaType().isAssignableFrom(from)) {
            throw new IllegalStateException("Wrong path.");
        }
        from = attribute.getJavaType();
    }
}

From source file:com.dbs.sdwt.jpa.JpaUtil.java

@SuppressWarnings("rawtypes")
public void verifyPath(List<Attribute<?, ?>> path) {
    List<Attribute<?, ?>> attributes = newArrayList(path);
    Class<?> from = null;//w  ww.  j  a  va2s  .  co  m
    if (attributes.get(0).isCollection()) {
        from = ((PluralAttribute) attributes.get(0)).getElementType().getJavaType();
    } else {
        from = attributes.get(0).getJavaType();
    }
    attributes.remove(0);
    for (Attribute<?, ?> attribute : attributes) {
        if (!attribute.getDeclaringType().getJavaType().isAssignableFrom(from)) {
            throw new IllegalStateException("Wrong path.");
        }
        from = attribute.getJavaType();
    }
}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java

/**
 * modify//from w w  w .j a  v a2s.  c  o  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: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;/*  ww w.  j  ava  2 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:org.batoo.jpa.core.impl.model.IdentifiableTypeImpl.java

/**
 * {@inheritDoc}/*ww  w  .  j a  va  2 s  .c o m*/
 * 
 */
@Override
protected void addAttributes(ManagedTypeMetadata entityMetadata) {
    if (this.supertype != null) {
        for (Attribute<? super X, ?> attribute : this.supertype.getAttributes()) {
            if ((attribute.getDeclaringType() instanceof MappedSuperclassTypeImpl)
                    && (this instanceof EntityTypeImpl)) {
                attribute = ((AttributeImpl<? super X, ?>) attribute).clone((EntityTypeImpl<X>) this);
            }

            this.addAttribute((AttributeImpl<? super X, ?>) attribute);
        }
    }

    super.addAttributes(entityMetadata);
}