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.JpaDao.java

/**
 * Null References on one to many and one to one associations.
 * Will only work if association has annotated with a mappedBy attribute.
 * //w ww .j  a  v  a  2  s. c  o 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.impetus.client.neo4j.GraphEntityMapper.java

/**
 * /*from  w  ww .j a v  a  2  s  . c  o m*/
 * Converts a {@link Node} instance to entity object
 */
public Object getEntityFromNode(Node node, EntityMetadata m) {
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(m.getPersistenceUnit());
    EntityType entityType = metaModel.entity(m.getEntityClazz());

    // Iterate over, entity attributes
    Set<Attribute> attributes = entityType.getSingularAttributes();

    Object entity = null;

    try {
        // entity = m.getEntityClazz().newInstance();

        for (Attribute attribute : attributes) {
            Field field = (Field) attribute.getJavaMember();
            String columnName = ((AbstractAttribute) attribute).getJPAColumnName();

            // Set Entity level properties
            if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())
                    && m.getIdAttribute().getJavaType().equals(field.getType())) {
                Object idValue = deserializeIdAttributeValue(m, (String) node.getProperty(columnName));
                if (idValue != null) {
                    entity = initialize(m, entity);
                    PropertyAccessorHelper.set(entity, field, idValue);
                }
            } else if (!attribute.isCollection() && !attribute.isAssociation()
                    && !((AbstractAttribute) m.getIdAttribute()).getJPAColumnName().equals(columnName)) {
                Object columnValue = node.getProperty(columnName, null);
                if (columnValue != null) {
                    entity = initialize(m, entity);
                    PropertyAccessorHelper.set(entity, field, fromNeo4JObject(columnValue, field));
                }
            }
        }

        if (entity != null && !metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())) {
            Object rowKey = node.getProperty(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName());
            if (rowKey != null) {
                PropertyAccessorHelper.setId(entity, m,
                        fromNeo4JObject(rowKey, (Field) m.getIdAttribute().getJavaMember()));
            }
        }
    } catch (NotFoundException e) {
        log.info(e.getMessage());
        return null;
    }

    return entity;
}

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

/**
 * /* w ww .j a  va  2s . c  o  m*/
 * Converts a {@link Relationship} object to corresponding entity object
 */
public Object getEntityFromRelationship(Relationship relationship, EntityMetadata topLevelEntityMetadata,
        Relation relation) {
    EntityMetadata relationshipEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
            relation.getMapKeyJoinClass());

    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(relationshipEntityMetadata.getPersistenceUnit());
    EntityType entityType = metaModel.entity(relationshipEntityMetadata.getEntityClazz());

    // Iterate over, entity attributes
    Set<Attribute> attributes = entityType.getSingularAttributes();

    Object entity = null;

    try {
        // entity =
        // relationshipEntityMetadata.getEntityClazz().newInstance();

        for (Attribute attribute : attributes) {
            Field field = (Field) attribute.getJavaMember();
            String columnName = ((AbstractAttribute) attribute).getJPAColumnName();

            // Set Entity level properties
            if (metaModel.isEmbeddable(relationshipEntityMetadata.getIdAttribute().getBindableJavaType())
                    && relationshipEntityMetadata.getIdAttribute().getJavaType().equals(field.getType())) {
                Object idValue = deserializeIdAttributeValue(relationshipEntityMetadata,
                        (String) relationship.getProperty(columnName));
                if (idValue != null) {
                    entity = initialize(relationshipEntityMetadata, entity);
                    PropertyAccessorHelper.set(entity, field, idValue);
                }
            } else if (!attribute.isCollection() && !attribute.isAssociation()
                    && !field.getType().equals(topLevelEntityMetadata.getEntityClazz())
                    && !field.getType().equals(relation.getTargetEntity())) {
                Object value = relationship.getProperty(columnName, null);
                if (value != null) {
                    entity = initialize(relationshipEntityMetadata, entity);
                    PropertyAccessorHelper.set(entity, field, fromNeo4JObject(value, field));
                }
            }
        }

        if (entity != null
                && !metaModel.isEmbeddable(relationshipEntityMetadata.getIdAttribute().getBindableJavaType())) {
            Object rowKey = relationship.getProperty(
                    ((AbstractAttribute) relationshipEntityMetadata.getIdAttribute()).getJPAColumnName());
            if (rowKey != null) {
                PropertyAccessorHelper.setId(entity, relationshipEntityMetadata, fromNeo4JObject(rowKey,
                        (Field) relationshipEntityMetadata.getIdAttribute().getJavaMember()));
            }
        }
    } catch (NotFoundException e) {
        log.info(e.getMessage());
        return null;
    }

    return entity;
}

From source file:com.impetus.client.cassandra.schemamanager.CassandraSchemaManager.java

/**
 * Creates the typefor embeddables.//  w  ww.j ava 2  s .  com
 * 
 */
private void createTypeforEmbeddables() {
    if (!createdPuEmbeddables.contains(puMetadata.getPersistenceUnitName())) {
        CQLTranslator translator = new CQLTranslator();

        Map<String, String> embNametoUDTQuery = new HashMap<String, String>();
        Map<String, List<String>> embNametoDependentList = new HashMap<String, List<String>>();

        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                .getMetamodel(puMetadata.getPersistenceUnitName());

        Iterator iter = metaModel.getEmbeddables().iterator();
        while (iter.hasNext()) {
            List<String> childEmb = new ArrayList<String>();

            String typeQuery = CQLTranslator.CREATE_TYPE;
            EmbeddableType embeddedColumn = (EmbeddableType) iter.next();
            if (!embeddedColumn.getPersistenceType().equals(PersistenceType.EMBEDDABLE)) {
                continue;
            }

            typeQuery = StringUtils.replace(typeQuery, CQLTranslator.TYPE, translator
                    .ensureCase(new StringBuilder(), embeddedColumn.getJavaType().getSimpleName(), false)
                    .toString());

            StringBuilder typeQueryBuilder = new StringBuilder();

            for (Object column : embeddedColumn.getAttributes()) {

                Attribute columnAttribute = (Attribute) column;
                Field f = (Field) columnAttribute.getJavaMember();

                if (columnAttribute.getJavaType().isAnnotationPresent(Embeddable.class)) {
                    // handle embeddable
                    String cqlType = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE
                            + columnAttribute.getJavaType().getSimpleName() + Constants.ESCAPE_QUOTE
                            + Constants.STR_GT;
                    translator.appendColumnName(typeQueryBuilder, columnAttribute.getName(), cqlType);
                    typeQueryBuilder.append(Constants.SPACE_COMMA);
                    childEmb.add(columnAttribute.getJavaType().getSimpleName());
                } else if (columnAttribute.isCollection()) {
                    // handle element collection with embeddables
                    handleElementCollectionAttribute(translator, columnAttribute, typeQueryBuilder);
                    if (!MetadataUtils.isBasicElementCollectionField((Field) columnAttribute.getJavaMember())) {
                        childEmb.add(
                                ((AbstractAttribute) columnAttribute).getBindableJavaType().getSimpleName());
                    }

                } else {
                    String cqlType = null;
                    String dataType = CassandraValidationClassMapper.getValidationClass(f.getType(), true);
                    cqlType = translator.getCQLType(dataType);
                    // check for JPA names
                    translator.appendColumnName(typeQueryBuilder,
                            ((AbstractAttribute) columnAttribute).getJPAColumnName(), cqlType);
                    typeQueryBuilder.append(Constants.SPACE_COMMA);

                }

            }
            typeQueryBuilder = replaceColumnsAndStripLastChar(typeQuery, typeQueryBuilder);
            typeQueryBuilder.append(CQLTranslator.CLOSE_BRACKET);
            embNametoUDTQuery.put(embeddedColumn.getJavaType().getSimpleName(), typeQueryBuilder.toString());
            embNametoDependentList.put(embeddedColumn.getJavaType().getSimpleName(), childEmb);
            // run query final

        }
        postProcessEmbedded(embNametoUDTQuery, embNametoDependentList);
        createdPuEmbeddables.add(puMetadata.getPersistenceUnitName());
    }
}

From source file:nl.strohalm.cyclos.utils.database.DatabaseQueryHandler.java

@SuppressWarnings("unchecked")
public void resolveReferences(final Entity entity) {
    final EntityType meta = getClassMetaData(entity);
    Set<Attribute> attrs = meta.getAttributes();
    for (Attribute attr : attrs) {
        final Attribute type = attr;
        final String name = attr.getName();
        if (type instanceof EntityType) {
            // Properties that are relationships to other entities
            Entity rel = PropertyHelper.get(entity, name);
            if (rel instanceof EntityReference) {
                rel = DatabaseUtil.getCurrentEntityManager().find(EntityHelper.getRealClass(rel), rel.getId());
                PropertyHelper.set(entity, name, rel);
            }// w w  w .ja v  a2 s  . co  m
        } else if (type.isCollection()) {
            // Properties that are collections of other entities
            final Collection<?> current = PropertyHelper.get(entity, name);
            if (current != null /*&& !(current instanceof PersistentCollection)*/) {
                // We must check that the collection is made of entities, since Hibernate supports collections os values
                boolean isEntityCollection = true;
                final Collection<Entity> resolved = ClassHelper.instantiate(current.getClass());
                for (final Object object : current) {
                    if (object != null && !(object instanceof Entity)) {
                        isEntityCollection = false;
                        break;
                    }
                    Entity e = (Entity) object;
                    if (object instanceof EntityReference) {
                        e = DatabaseUtil.getCurrentEntityManager().find(EntityHelper.getRealClass(e),
                                e.getId());
                    }
                    resolved.add(e);
                }
                if (isEntityCollection) {
                    PropertyHelper.set(entity, name, resolved);
                }
            }
        }
    }
}

From source file:ru.savvy.jpafilterbuilder.FilterCriteriaBuilder.java

/**
 * Returns Java type of the fieldName/* w w  w .  j  a va2 s. c o  m*/
 *
 * @param fieldName
 * @return
 * @throws IllegalArgumentException if fieldName isn't valid for given
 *                                  entity
 */
public Class<?> getJavaType(String fieldName) {

    String[] compoundField = fieldName.split("\\.");
    EntityType et = metamodel.entity(clazz);

    for (int i = 0; i < compoundField.length; i++) {
        if (i < (compoundField.length - 1)) {
            try {
                Attribute att = et.getAttribute(compoundField[i]);
                if (att.isCollection()) {
                    et = metamodel.entity(getPluralJavaType(et, compoundField[i]));
                } else {
                    et = metamodel.entity(et.getAttribute(compoundField[i]).getJavaType());
                }
            } catch (IllegalArgumentException | IllegalStateException e) {
                throw new IllegalArgumentException("Illegal field name " + fieldName + " (" + compoundField[i]
                        + ") for root type " + clazz);
            }
        } else {
            try {
                return et.getAttribute(compoundField[i]).getJavaType();
            } catch (IllegalArgumentException | IllegalStateException e) {
                throw new IllegalArgumentException("Illegal field name " + fieldName + " (" + compoundField[i]
                        + ") for root type " + clazz);
            }
        }
    }
    return null; // should never be reached
}