Example usage for javax.persistence.metamodel Attribute isAssociation

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

Introduction

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

Prototype

boolean isAssociation();

Source Link

Document

Is the attribute an association.

Usage

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

/**
 * Gets the mappedBy value from an attribute
 * @param attribute attribute//  ww w .  jav a  2 s .  c o m
 * @return mappedBy value or null if none.
 */
public static String getMappedBy(Attribute<?, ?> attribute) {
    String mappedBy = null;

    if (attribute.isAssociation()) {
        Annotation[] annotations = null;
        Member member = attribute.getJavaMember();
        if (member instanceof Field) {
            annotations = ((Field) member).getAnnotations();
        } else if (member instanceof Method) {
            annotations = ((Method) member).getAnnotations();
        }

        for (Annotation a : annotations) {
            if (a.annotationType().equals(OneToMany.class)) {
                mappedBy = ((OneToMany) a).mappedBy();
                break;
            } else if (a.annotationType().equals(ManyToMany.class)) {
                mappedBy = ((ManyToMany) a).mappedBy();
                break;
            } else if (a.annotationType().equals(OneToOne.class)) {
                mappedBy = ((OneToOne) a).mappedBy();
                break;
            }
        }
    }

    return "".equals(mappedBy) ? null : mappedBy;
}

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

/**
 * Checks whether an entity with given metadata contains a collection field
 * /*from   w  w w .  jav a2 s  . 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:org.jdal.dao.jpa.JpaUtils.java

/**
 * Initialize a entity. //from  w w  w  .java  2s. c  o 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:de.micromata.genome.jpa.metainf.MetaInfoUtils.java

/**
 * Gets the column meta data.//from   www .j  a v a  2 s  . com
 *
 * @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.impetus.client.rdbms.query.RDBMSEntityReader.java

/**
 * Gets the sql query from jpa.//  ww w. j a v  a 2s  .  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
 * /*  ww w .  j a  va  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   ww  w . j  a  v  a 2s.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;
}

From source file:com.impetus.kundera.client.cassandra.dsdriver.DSClient.java

/**
 * Iterator columns./* ww  w . j a v  a2 s .c  o  m*/
 * 
 * @param metadata
 *            the metadata
 * @param metamodel
 *            the metamodel
 * @param entityType
 *            the entity type
 * @param relationalValues
 *            the relational values
 * @param entity
 *            the entity
 * @param row
 *            the row
 * @param columnDefIter
 *            the column def iter
 * @return the object
 */
private Object iteratorColumns(EntityMetadata metadata, MetamodelImpl metamodel, EntityType entityType,
        Map<String, Object> relationalValues, Object entity, Row row, Iterator<Definition> columnDefIter) {
    while (columnDefIter.hasNext()) {
        Definition columnDef = columnDefIter.next();
        final String columnName = columnDef.getName(); // column name

        DataType dataType = columnDef.getType(); // data type

        if (metadata.getRelationNames() != null && metadata.getRelationNames().contains(columnName)
                && !columnName.equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName())) {
            Object relationalValue = DSClientUtilities.assign(row, null, metadata, dataType.getName(),
                    entityType, columnName, null, metamodel);
            relationalValues.put(columnName, relationalValue);
        } else {
            String fieldName = columnName
                    .equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName())
                            ? metadata.getIdAttribute().getName()
                            : metadata.getFieldName(columnName);
            Attribute attribute = fieldName != null ? entityType.getAttribute(fieldName) : null;

            if (attribute != null) {
                if (!attribute.isAssociation()) {
                    entity = DSClientUtilities.assign(row, entity, metadata, dataType.getName(), entityType,
                            columnName, null, metamodel);
                }
            } else if (metamodel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {
                entity = populateCompositeId(metadata, entity, columnName, row, metamodel,
                        metadata.getIdAttribute(), metadata.getEntityClazz(), dataType);
            } else {
                entity = DSClientUtilities.assign(row, entity, metadata, dataType.getName(), entityType,
                        columnName, null, metamodel);
            }
        }
    }
    return entity;
}

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

/**
 * /*from  w  w w .  ja va2 s.c  om*/
 * 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.oraclenosql.OracleNoSQLClient.java

/**
 * Iterate and store attributes.//from   ww  w . ja v a  2 s.  co m
 * 
 * @param entity
 *            JPA entity.
 * @param metamodel
 *            JPA meta model.
 * @param row
 *            kv row.
 * @param attributes
 *            JPA attributes.
 * @param schemaTable
 *            the schema table
 * @param metadata
 *            the metadata
 */
private void process(Object entity, MetamodelImpl metamodel, Row row, Set<Attribute> attributes,
        Table schemaTable, EntityMetadata metadata) {

    for (Attribute attribute : attributes) {
        // by pass association.
        if (!attribute.isAssociation()) {
            // in case of embeddable id.
            if (attribute.equals(metadata.getIdAttribute())
                    && metamodel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) {
                processEmbeddableAttribute(entity, metamodel, row, schemaTable, metadata, attribute);
            } else {
                if (metamodel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) {
                    processEmbeddableAttribute(entity, metamodel, row, schemaTable, metadata, attribute);
                } else {
                    setField(row, schemaTable, entity, attribute);
                }
            }
        }
    }
}