Example usage for javax.persistence.metamodel Attribute isCollection

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

Introduction

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

Prototype

boolean isCollection();

Source Link

Document

Is the attribute collection-valued (represents a Collection, Set, List, or Map).

Usage

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

/**
 * Test if attribute is type or in collections has element type
 * @param attribute attribute to test/*from  ww w.j av a 2  s.c  o m*/
 * @param clazz Class to test
 * @return true if clazz is asignable from type or element type
 */
public static boolean isTypeOrElementType(Attribute<?, ?> attribute, Class<?> clazz) {
    if (attribute.isCollection()) {
        return clazz.isAssignableFrom(((CollectionAttribute<?, ?>) attribute).getBindableJavaType());
    }

    return clazz.isAssignableFrom(attribute.getJavaType());
}

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

/**
 * Initialize a entity. //ww  w . j  a v a2  s .co m
 * @param em entity manager to use
 * @param entity entity to initialize
 * @param depth max depth on recursion
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void initialize(EntityManager em, Object entity, int depth) {
    // return on nulls, depth = 0 or already initialized objects
    if (entity == null || depth == 0) {
        return;
    }

    PersistenceUnitUtil unitUtil = em.getEntityManagerFactory().getPersistenceUnitUtil();
    EntityType entityType = em.getMetamodel().entity(entity.getClass());
    Set<Attribute> attributes = entityType.getDeclaredAttributes();

    Object id = unitUtil.getIdentifier(entity);

    if (id != null) {
        Object attached = em.find(entity.getClass(), unitUtil.getIdentifier(entity));

        for (Attribute a : attributes) {
            if (!unitUtil.isLoaded(entity, a.getName())) {
                if (a.isCollection()) {
                    intializeCollection(em, entity, attached, a, depth);
                } else if (a.isAssociation()) {
                    intialize(em, entity, attached, a, depth);
                }
            }
        }
    }
}

From source file:com.impetus.kundera.metadata.MetadataUtils.java

/**
 * Checks whether an entity with given metadata contains a collection field
 * //from w w  w  .  j a  va 2s .co m
 * @param m
 * @return
 */
public static boolean containsBasicElementCollectionField(final EntityMetadata m,
        final KunderaMetadata kunderaMetadata) {
    Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());
    EntityType entityType = metaModel.entity(m.getEntityClazz());
    Iterator<Attribute> iter = entityType.getAttributes().iterator();
    while (iter.hasNext()) {
        Attribute attr = iter.next();

        if (attr.isCollection() && !attr.isAssociation()
                && isBasicElementCollectionField((Field) attr.getJavaMember())) {
            return true;
        }
    }
    return false;
}

From source file:com.ocs.dynamo.dao.query.JpaQueryBuilder.java

private static boolean isCollectionFetch(FetchParent<?, ?> parent) {
    boolean result = false;

    for (Fetch<?, ?> fetch : parent.getFetches()) {
        Attribute<?, ?> attribute = fetch.getAttribute();

        boolean nested = isCollectionFetch(fetch);
        result = result || attribute.isCollection() || nested;
    }//from w  w  w. j  a v  a 2  s .c o  m
    return result;
}

From source file:de.micromata.genome.jpa.metainf.MetaInfoUtils.java

/**
 * Gets the column meta data.//from ww  w.  j  ava 2s  .  c  o 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: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  2s. com*/
    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 .  j  a  v a  2s.c  o  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:com.impetus.client.rdbms.query.RDBMSEntityReader.java

/**
 * Gets the sql query from jpa./*from  www  .  j a  va 2 s . com*/
 * 
 * @param entityMetadata
 *            the entity metadata
 * @param relations
 *            the relations
 * @param primaryKeys
 *            the primary keys
 * @return the sql query from jpa
 */
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();
}

From source file:com.impetus.client.neo4j.GraphEntityMapper.java

/**
 * Populates Node properties from Entity object
 * //from  w w w  .  jav a 2 s .c o m
 * @param entity
 * @param m
 * @param node
 */
private void populateNodeProperties(Object entity, EntityMetadata m, Node node) {
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m.getPersistenceUnit());
    EntityType entityType = metaModel.entity(m.getEntityClazz());

    // Iterate over entity attributes
    Set<Attribute> attributes = entityType.getSingularAttributes();
    for (Attribute attribute : attributes) {
        Field field = (Field) attribute.getJavaMember();

        // Set Node level properties
        if (!attribute.isCollection() && !attribute.isAssociation()
                && !((SingularAttribute) attribute).isId()) {
            String columnName = ((AbstractAttribute) attribute).getJPAColumnName();
            Object value = PropertyAccessorHelper.getObject(entity, field);
            if (value != null) {
                node.setProperty(columnName, toNeo4JProperty(value));
            }
        }
    }
}

From source file:com.impetus.client.neo4j.GraphEntityMapper.java

/**
 * Creates a Map containing all properties (and their values) for a given
 * entity/*from  w w w . j ava2s .  c  o  m*/
 * 
 * @param entity
 * @param m
 * @return
 */
public Map<String, Object> createNodeProperties(Object entity, EntityMetadata m) {
    Map<String, Object> props = new HashMap<String, Object>();

    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m.getPersistenceUnit());

    EntityType entityType = metaModel.entity(m.getEntityClazz());

    // Iterate over entity attributes
    Set<Attribute> attributes = entityType.getSingularAttributes();
    for (Attribute attribute : attributes) {
        Field field = (Field) attribute.getJavaMember();

        // Set Node level properties
        if (!attribute.isCollection() && !attribute.isAssociation()) {

            String columnName = ((AbstractAttribute) attribute).getJPAColumnName();
            Object value = PropertyAccessorHelper.getObject(entity, field);
            if (value != null) {
                props.put(columnName, toNeo4JProperty(value));
            }
        }
    }
    return props;
}