Example usage for javax.persistence.metamodel Attribute getPersistentAttributeType

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

Introduction

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

Prototype

PersistentAttributeType getPersistentAttributeType();

Source Link

Document

Return the persistent attribute type for the attribute.

Usage

From source file:org.jdal.dao.jpa.JpaUtils.java

/**
 * Get all attributes where type or element type is assignable from class and has persistent type
 * @param type entity type//ww w.  j a  v a  2  s .co m
 * @param persistentType persistentType
 * @param clazz class
 * @return Set with matching attributes
 */
public static Set<Attribute<?, ?>> getAttributes(EntityType<?> type, PersistentAttributeType persistentType,
        Class<?> clazz) {
    Set<Attribute<?, ?>> attributes = new HashSet<Attribute<?, ?>>();

    for (Attribute<?, ?> a : type.getAttributes()) {
        if (a.getPersistentAttributeType() == persistentType && isTypeOrElementType(a, clazz)) {
            attributes.add(a);
        }
    }

    return attributes;
}

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.ja  v a 2s.  c o m
    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) {/* ww  w  .  ja  va  2 s. co m*/
    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:de.micromata.genome.jpa.metainf.MetaInfoUtils.java

/**
 * Gets the column meta data.// w  ww .ja v a2 s. co  m
 *
 * @param entity the entity
 * @param entityClass the entity class
 * @param at the at
 * @param pdo the pdo
 * @return the column meta data
 */
public static ColumnMetadata getColumnMetaData(EntityMetadataBean entity, Class<?> entityClass,
        Attribute<?, ?> at, Optional<PropertyDescriptor> pdo) {
    ColumnMetadataBean ret = new ColumnMetadataBean(entity);
    ret.setName(at.getName());
    ret.setJavaType(at.getJavaType());
    ret.setAssociation(at.isAssociation());
    ret.setCollection(at.isCollection());

    if (at instanceof PluralAttribute) {
        PluralAttribute pa = (PluralAttribute) at;
        Type eltype = pa.getElementType();
        CollectionType coltype = pa.getCollectionType();
    }

    Member jm = at.getJavaMember();
    // TODO maybe handle this.
    at.getPersistentAttributeType();
    if ((jm instanceof AccessibleObject) == false) {
        LOG.warn("Column " + at.getName() + " ha no valid Java Member");
        return ret;
    }
    AccessibleObject ao = (AccessibleObject) jm;
    getGetterSetter(entityClass, ao, pdo, ret);
    ret.setAnnotations(getFieldAndMemberAnnots(entityClass, ao));
    if (ret.getAnnotations().stream().filter((anot) -> anot.getClass() == Transient.class).count() > 0) {
        return null;
    }
    Column colc = ao.getAnnotation(Column.class);
    if (colc == null) {
        ret.setMaxLength(255);
        return ret;
    }
    String name = colc.name();
    if (StringUtils.isEmpty(name) == true) {
        ret.setDatabaseName(ret.getName());
    } else {
        ret.setDatabaseName(name);
    }
    ret.setMaxLength(colc.length());
    ret.setUnique(colc.unique());
    ret.setColumnDefinition(colc.columnDefinition());
    ret.setInsertable(colc.insertable());
    ret.setNullable(colc.nullable());
    ret.setPrecision(colc.precision());
    ret.setScale(colc.scale());
    return ret;
}

From source file:bq.jpa.demo.metadata.service.MetadataService.java

public void doMD() {
    Metamodel md = em.getMetamodel();//from w  w  w.ja v a  2 s . co m
    EntityType<Employee> employee = md.entity(Employee.class);
    for (Attribute<? super Employee, ?> attr : employee.getAttributes()) {
        System.out.println(attr.getName() + " | " + attr.getJavaType().getName() + " | "
                + attr.getPersistentAttributeType());
    }
}

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 w  w  .j av a2 s  .c  om
 * @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: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  .  java 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: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 .jav  a2s.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.evolveum.midpoint.repo.sql.helpers.ObjectDeltaUpdater.java

private void handleAttribute(Attribute attribute, Object bean, ItemDelta delta, PrismObject prismObject,
        PrismIdentifierGenerator idGenerator) {
    Method method = (Method) attribute.getJavaMember();

    switch (attribute.getPersistentAttributeType()) {
    case BASIC:/*from w w w.j  av a 2 s. c  o  m*/
    case EMBEDDED:
        handleBasicOrEmbedded(bean, delta, attribute);
        break;
    case MANY_TO_MANY:
        // not used in our mappings
        throw new SystemException("Don't know how to handle @ManyToMany relationship, should not happen");
    case ONE_TO_ONE:
        // assignment extension is handled separately
        break;
    case MANY_TO_ONE:
        // this can't be in delta (probably)
        throw new SystemException("Don't know how to handle @ManyToOne relationship, should not happen");
    case ONE_TO_MANY:
        // object extension is handled separately, only {@link Container} and references are handled here
        Collection oneToMany = (Collection) invoke(bean, method);
        handleOneToMany(oneToMany, delta, attribute, bean, prismObject, idGenerator);
        break;
    case ELEMENT_COLLECTION:
        Collection elementCollection = (Collection) invoke(bean, method);
        handleElementCollection(elementCollection, delta, attribute, bean, prismObject, idGenerator);
        break;
    }
}