Example usage for javax.persistence.metamodel EntityType getAttributes

List of usage examples for javax.persistence.metamodel EntityType getAttributes

Introduction

In this page you can find the example usage for javax.persistence.metamodel EntityType getAttributes.

Prototype

Set<Attribute<? super X, ?>> getAttributes();

Source Link

Document

Return the attributes of the managed type.

Usage

From source file:com.impetus.client.cassandra.thrift.CQLTranslator.java

/**
 * On translation.//from w  w  w. ja  v  a  2  s .c om
 * 
 * @param record
 *            the record
 * @param m
 *            the m
 * @param type
 *            the type
 * @param metaModel
 *            the meta model
 * @param entityClazz
 *            the entity clazz
 * @param entityType
 *            the entity type
 * @param builders
 *            the builders
 * @param columnBuilders
 *            the column builders
 * @param externalProperties
 *            the external properties
 * @param kunderaMetadata
 *            the kundera metadata
 */
private void onTranslation(final Object record, final EntityMetadata m, TranslationType type,
        MetamodelImpl metaModel, Class entityClazz, EntityType entityType, Map<String, StringBuilder> builders,
        Map<String, StringBuilder> columnBuilders, Map<String, Object> externalProperties,
        final KunderaMetadata kunderaMetadata) {
    Set<Attribute> attributes = entityType.getAttributes();
    Iterator<Attribute> iterator = attributes.iterator();
    while (iterator.hasNext()) {
        Attribute attribute = iterator.next();

        // Populating table name.
        String tableName = ((AbstractAttribute) attribute).getTableName() != null
                ? ((AbstractAttribute) attribute).getTableName()
                : m.getTableName();

        StringBuilder columnBuilder = columnBuilders.get(tableName);
        if (columnBuilder == null) {
            columnBuilder = new StringBuilder();
            columnBuilders.put(tableName, columnBuilder);
        }

        StringBuilder builder = builders.get(tableName);
        if (builder == null) {
            builder = new StringBuilder();
            builders.put(tableName, builder);
        }
        Field field = (Field) attribute.getJavaMember();
        if (!attribute.equals(m.getIdAttribute()) && !((AbstractAttribute) attribute).getJPAColumnName()
                .equals(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName())) {
            if (metaModel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) {
                // create embedded entity persisting format
                if (field.isAnnotationPresent(ElementCollection.class)) {
                    // handle embeddable collection
                    // check list, map, set
                    // build embedded value
                    StringBuilder elementCollectionValue = buildElementCollectionValue(field, record, metaModel,
                            attribute);
                    columnBuilder.append(Constants.ESCAPE_QUOTE);
                    columnBuilder.append(((AbstractAttribute) attribute).getJPAColumnName());
                    columnBuilder.append(Constants.ESCAPE_QUOTE);
                    columnBuilder.append(Constants.COMMA);
                    builder.append(elementCollectionValue);
                    builder.append(Constants.COMMA);
                } else {
                    EmbeddableType embeddableKey = metaModel.embeddable(field.getType());
                    Object embeddableKeyObj = PropertyAccessorHelper.getObject(record, field);
                    if (embeddableKeyObj != null) {

                        StringBuilder embeddedValueBuilder = new StringBuilder(Constants.OPEN_CURLY_BRACKET);

                        for (Field embeddableColumn : field.getType().getDeclaredFields()) {
                            if (!ReflectUtils.isTransientOrStatic(embeddableColumn)) {
                                AbstractAttribute subAttribute = (AbstractAttribute) embeddableKey
                                        .getAttribute(embeddableColumn.getName());
                                if (metaModel.isEmbeddable(subAttribute.getBindableJavaType())) {
                                    // construct map; recursive
                                    // send attribute
                                    if (embeddableColumn.isAnnotationPresent(ElementCollection.class)) {
                                        // build element collection value
                                        StringBuilder elementCollectionValue = buildElementCollectionValue(
                                                embeddableColumn, embeddableKeyObj, metaModel,
                                                (Attribute) subAttribute);

                                        appendColumnName(embeddedValueBuilder,
                                                ((AbstractAttribute) (embeddableKey
                                                        .getAttribute(embeddableColumn.getName())))
                                                                .getJPAColumnName());
                                        embeddedValueBuilder.append(Constants.COLON);
                                        embeddedValueBuilder.append(elementCollectionValue);
                                    } else {
                                        buildEmbeddedValue(embeddableKeyObj, metaModel, embeddedValueBuilder,
                                                (SingularAttribute) subAttribute);
                                    }
                                } else {
                                    // append key value
                                    appendColumnName(embeddedValueBuilder,
                                            ((AbstractAttribute) (embeddableKey
                                                    .getAttribute(embeddableColumn.getName())))
                                                            .getJPAColumnName());
                                    embeddedValueBuilder.append(Constants.COLON);
                                    appendColumnValue(embeddedValueBuilder, embeddableKeyObj, embeddableColumn);
                                }
                                embeddedValueBuilder.append(Constants.COMMA);
                            }
                        }
                        // strip last char and append '}'
                        embeddedValueBuilder.deleteCharAt(embeddedValueBuilder.length() - 1);
                        embeddedValueBuilder.append(Constants.CLOSE_CURLY_BRACKET);
                        // add to columnbuilder and builder
                        columnBuilder.append(Constants.ESCAPE_QUOTE);
                        columnBuilder.append(((AbstractAttribute) attribute).getJPAColumnName());
                        columnBuilder.append(Constants.ESCAPE_QUOTE);
                        columnBuilder.append(Constants.COMMA);
                        builder.append(embeddedValueBuilder);
                        builder.append(Constants.COMMA);
                        // end if
                    }
                }
            } else if (!ReflectUtils.isTransientOrStatic(field) && !attribute.isAssociation()) {
                onTranslation(type, builder, columnBuilder, ((AbstractAttribute) attribute).getJPAColumnName(),
                        record, field);
            }
        }
    }

    for (String tableName : columnBuilders.keySet()) {
        translateCompositeId(record, m, type, metaModel, builders, columnBuilders, externalProperties,
                kunderaMetadata, tableName, m.getIdAttribute());
    }

    // on inherited columns.
    onDiscriminatorColumn(builders.get(m.getTableName()), columnBuilders.get(m.getTableName()), entityType);
}

From source file:com.impetus.client.redis.RedisClient.java

/**
 * Wraps entity attributes into byte[] and return instance of attribute
 * wrapper.//w w w.ja  va  2 s  .  c  o  m
 * 
 * @param entityMetadata
 * @param entity
 * @return
 */
private AttributeWrapper wrap(EntityMetadata entityMetadata, Object entity) {
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(entityMetadata.getPersistenceUnit());

    EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());
    Set<Attribute> attributes = entityType.getAttributes();

    // attributes can be null??? i guess NO
    AttributeWrapper wrapper = new AttributeWrapper(attributes.size());

    List<String> relationNames = entityMetadata.getRelationNames();

    // PropertyAccessorHelper.get(entity,
    for (Attribute attr : attributes) {
        if (/* !entityMetadata.getIdAttribute().equals(attr) && */!attr.isAssociation()) {
            if (metaModel.isEmbeddable(((AbstractAttribute) attr).getBindableJavaType())) {
                EmbeddableType embeddableAttribute = metaModel
                        .embeddable(((AbstractAttribute) attr).getBindableJavaType());

                Object embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) attr.getJavaMember());

                Set<Attribute> embeddedAttributes = embeddableAttribute.getAttributes();

                for (Attribute attrib : embeddedAttributes) {
                    addToWrapper(entityMetadata, wrapper, embeddedObject, attrib, attr);
                }

            } else {
                addToWrapper(entityMetadata, wrapper, entity, attr);
            }
        } else if (attributes.size() == 1) // means it is only a key! weird
                                           // but possible negative
                                           // scenario
        {
            byte[] value = PropertyAccessorHelper.get(entity, (Field) attr.getJavaMember());
            byte[] name;
            name = getEncodedBytes(((AbstractAttribute) attr).getJPAColumnName());

            // add column name as key and value as value
            wrapper.addColumn(name, value);

        }
    }

    return wrapper;
}

From source file:com.impetus.client.oraclenosql.OracleNoSQLClient.java

/**
 * Scroll and populate.//from  w  ww  . j  ava  2  s. co  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.impetus.client.cassandra.CassandraClientBase.java

/**
 * Return update query string for given entity intended for counter column
 * family.//www.ja  v a 2 s. c  o  m
 * 
 * @param entityMetadata
 *            the entity metadata
 * @param entity
 *            the entity
 * @param cassandra_client
 *            the cassandra_client
 * @param rlHolders
 *            the rl holders
 * @return the list
 */
protected List<String> createUpdateQueryForCounter(EntityMetadata entityMetadata, Object entity,
        Cassandra.Client cassandra_client, List<RelationHolder> rlHolders) {
    Map<String, String> builders = new HashMap<String, String>();

    CQLTranslator translator = new CQLTranslator();

    Object rowId = PropertyAccessorHelper.getId(entity, entityMetadata);
    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
            .getMetamodel(entityMetadata.getPersistenceUnit());

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

    Set<Attribute> attributes = entityType.getAttributes();

    for (Attribute attrib : attributes) {
        if (!entityMetadata.getIdAttribute().getName().equals(attrib.getName())
                && !metaModel.isEmbeddable(attrib.getJavaType()) && !attrib.isAssociation()) {
            String tableName = ((AbstractAttribute) attrib).getTableName() != null
                    ? ((AbstractAttribute) attrib).getTableName()
                    : entityMetadata.getTableName();

            String queryString = builders.get(tableName);
            StringBuilder builder;
            if (queryString == null) {
                builder = new StringBuilder();
            } else {
                builder = new StringBuilder(queryString);
            }
            translator.buildSetClauseForCounters(builder, ((AbstractAttribute) attrib).getJPAColumnName(),
                    PropertyAccessorHelper.getObject(entity, attrib.getName()));
            builders.put(tableName, builder.toString());
        }
    }
    for (RelationHolder rl : rlHolders) {
        translator.buildSetClauseForCounters(new StringBuilder(builders.get(entityMetadata.getTableName())),
                rl.getRelationName(), rl.getRelationValue());
    }

    for (String tableName : builders.keySet()) {
        StringBuilder builder = new StringBuilder(builders.get(tableName));

        String update_Query = translator.UPDATE_QUERY;

        update_Query = StringUtils.replace(update_Query, CQLTranslator.COLUMN_FAMILY,
                translator.ensureCase(new StringBuilder(), tableName, false).toString());

        // strip last "," clause.
        builder.delete(builder.lastIndexOf(CQLTranslator.COMMA_STR), builder.length());

        builder.append(CQLTranslator.ADD_WHERE_CLAUSE);
        onWhereClause(entityMetadata, rowId, translator, builder, metaModel, entityMetadata.getIdAttribute());

        // strip last "AND" clause.
        builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());

        StringBuilder queryBuilder = new StringBuilder(update_Query);
        queryBuilder.append(CQLTranslator.ADD_SET_CLAUSE);
        queryBuilder.append(builder);

        if (log.isDebugEnabled()) {
            log.debug("Returning update query {}.", queryBuilder.toString());
        }

        builders.put(tableName, queryBuilder.toString());
    }
    return new ArrayList(builders.values());
}

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.j a v  a  2  s.  c  o  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:org.apache.click.extras.jpa.JpaForm.java

/**
 * Applies the <tt>ClassMetadata</tt> validation database meta data to the
 * form fields.//from   w  w w  . j a va 2s . c o m
 * <p/>
 * The field validation attributes include:
 * <ul>
 * <li>required - is a mandatory field and cannot be null</li>
 * </ul>
 */
protected void applyMetaData() {
    if (metaDataApplied) {
        return;
    }

    try {
        Class valueClass = Class.forName(classField.getValue());

        /*
        String classname = getClassname(valueClass);
                
        Metamodel metadata =
        ((HibernateEntityManagerFactory) getEntityManagerFactory()).getSessionFactory().getMetamodel(classname);
                
        String[] propertyNames = metadata.getPropertyNames();
                
        boolean[] propertyNullability = metadata.getPropertyNullability();
                 
        for (int i = 0; i < propertyNames.length; i++) {
        Field field = getField(propertyNames[i]);
        if (field != null) {
            field.setRequired(propertyNullability[i]);
        }
        }
         */
        Metamodel classMetadata = getEntityManager().getMetamodel();
        EntityType entityType = classMetadata.entity(valueClass);

        Set<SingularAttribute> attrs = entityType.getAttributes();

        for (SingularAttribute a : attrs) {
            Field field = getField(a.getName());
            if (field != null) {
                field.setRequired(a.isOptional());
            }
        }
    } catch (ClassNotFoundException cnfe) {
        throw new RuntimeException(cnfe);
    }

    metaDataApplied = true;
}

From source file:org.makersoft.activerecord.jpa.JPQL.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private Set<String> getColumns() {
    Metamodel metamodel = em().getMetamodel();
    Set<String> columns = new HashSet<String>();
    for (EntityType entityType : metamodel.getEntities()) {
        if (entityName.equals(entityType.getName())) {
            Set<Attribute> attributes = entityType.getAttributes();
            for (Attribute attribute : attributes) {
                columns.add(attribute.getName());
            }/* ww w.  ja va 2s . c  om*/
        }
    }

    return columns;
}