Java 类javax.persistence.metamodel.Attribute.PersistentAttributeType 实例源码

项目:jpasecurity    文件:MappingEvaluator.java   
public boolean visitJoin(Node node, Set<TypeDefinition> typeDefinitions) {
    if (node.jjtGetNumChildren() != 2) {
        return false;
    }
    Node pathNode = node.jjtGetChild(0);
    Node aliasNode = node.jjtGetChild(1);
    Alias rootAlias = new Alias(pathNode.jjtGetChild(0).toString());
    Class<?> rootType = getType(rootAlias, typeDefinitions);
    ManagedType<?> managedType = forModel(metamodel).filter(rootType);
    for (int i = 1; i < pathNode.jjtGetNumChildren(); i++) {
        Attribute<?, ?> attribute = managedType.getAttribute(pathNode.jjtGetChild(i).toString());
        if (attribute.getPersistentAttributeType() == PersistentAttributeType.BASIC) {
            throw new PersistenceException("Cannot navigate through basic property "
                    + pathNode.jjtGetChild(i) + " of path " + pathNode);
        }
        if (attribute.isCollection()) {
            PluralAttribute<?, ?, ?> pluralAttribute = (PluralAttribute<?, ?, ?>)attribute;
            managedType = (ManagedType<?>)pluralAttribute.getElementType();
        } else {
            managedType = (ManagedType<?>)((SingularAttribute)attribute).getType();
        }
    }
    typeDefinitions.add(new TypeDefinition(new Alias(aliasNode.toString()), managedType.getJavaType()));
    return false;
}
项目:invesdwin-context-persistence    文件:Attributes.java   
public static String extractNativeSqlColumnName(final Attribute<?, ?> attr) {
    switch (attr.getPersistentAttributeType()) {
    case BASIC:
    case EMBEDDED:
        return attr.getName();
    case ELEMENT_COLLECTION:
    case ONE_TO_ONE:
    case MANY_TO_ONE:
        return attr.getName() + ID_SUFFIX;
    case MANY_TO_MANY:
    case ONE_TO_MANY:
        throw new IllegalArgumentException(PersistentAttributeType.class.getSimpleName() + " ["
                + attr.getPersistentAttributeType() + "] is not supported!");
    default:
        throw UnknownArgumentException.newInstance(PersistentAttributeType.class, attr.getPersistentAttributeType());
    }
}
项目:breeze.server.java    文件:JPAMetadata.java   
/**
 * Gets the properties matching the given columns.  May be a component, but will not be an association.
 * @param entityType
 * @param columnNames
 * @return
 */
String[] getPropertyNamesForColumns(javax.persistence.metamodel.EntityType<?> entityType, String[] columnNames) {
    for (SingularAttribute attr : entityType.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == PersistentAttributeType.BASIC ||
                attr.getPersistentAttributeType() == PersistentAttributeType.EMBEDDED) {
            String[] columnArray = getColumnNames(attr);
            if (namesEqual(columnArray, columnNames)) return new String[] { attr.getName() };
        }
    }

    if (columnNames.length > 1)
    {
        // go one-by-one through columnNames, trying to find a matching property.
        // TODO: maybe this should split columnNames into all possible combinations of ordered subsets, and try those
        ArrayList<String> propList = new ArrayList<String>();
        String[] prop = new String[1];
        for (int i = 0; i < columnNames.length; i++)
        {
            prop[0] = columnNames[i];
            String[] names = getPropertyNamesForColumns(entityType, prop); // recursive call
            if (names != null) propList.addAll(Arrays.asList(names));
        }
        if (propList.size() > 0) return propList.toArray(new String[propList.size()]);
    }
    return null;
}
项目:query-utils    文件:EmbeddableUtil.java   
static Option<? extends Attribute<?,?>> unwrapEmbeddableAttribute(Attribute<?,?> attribute) {
    logger.debug("unwrapEmbeddableAttribute({})", attribute);

    Option<? extends Attribute<?,?>> ret = None();
    if (attribute == null || attribute instanceof PseudoAttribute) {
        ret = None();
    } else if (AttributeProxy.unwrap(PseudoAttribute.class, attribute).isDefined()) {
        ret = None();
    } else if (attribute instanceof JoiningAttribute && last(((JoiningAttribute) attribute).getAttributes()) instanceof PseudoAttribute) {
        ret = None();
    } else if (attribute.getPersistentAttributeType() == PersistentAttributeType.EMBEDDED) {
        ret = Some(attribute);
    } else if (attribute instanceof AdditionalQueryPerformingAttribute) {
        List<Attribute<?, ?>> params = ((AdditionalQueryPerformingAttribute)attribute).getConstructor().getParameters();
        if (params.size() == 1) {
            ret = unwrapEmbeddableAttribute(head(params));
        }
    }

    logger.debug("unwrapEmbeddableAttribute -> {}", ret);
    return ret;
}
项目:bootstrap    文件:AbstractSpecification.java   
@SuppressWarnings("unchecked")
private <X> PathImplementor<X> getNextPath(final String pathFragment, final From<?, ?> from) {
    PathImplementor<?> currentPath = (PathImplementor<?>) from.get(pathFragment);
    fixAlias(from, aliasCounter);

    // Handle join. Does not manage many-to-many
    if (currentPath.getAttribute().getPersistentAttributeType() != PersistentAttributeType.BASIC) {
        currentPath = getJoinPath(from, currentPath.getAttribute());
        if (currentPath == null) {
            // if no join, we create it
            currentPath = fixAlias(from.join(pathFragment, JoinType.LEFT), aliasCounter);
        }
    }
    return (PathImplementor<X>) currentPath;
}
项目:datatable-java    文件:DatatableHelper.java   
/**
 * Cree une expression Criteria API avec l'atribut de l'entité passé en parametre
 * 
 * @param root
 *            entité JPA contenant le champ
 * @param columnData
 *            nom du champ
 * @param clazz
 *            class du champ
 * @param <S>
 *            type du champ
 * @return l'expression de l'atribut
 */
public static <S> Path<S> getExpression(final Root<?> root, final String columnData, final Class<S> clazz) {
    if (!columnData.contains(DatatableSpecification.ATTRIBUTE_SEPARATOR)) {
        // columnData is like "attribute" so nothing particular to do
        return root.get(columnData);
    }
    // columnData is like "joinedEntity.attribute" so add a join clause
    final String[] values = columnData.split(DatatableSpecification.ESCAPED_ATTRIBUTE_SEPARATOR);
    final Attribute<?, ?> attribute = root.getModel().getAttribute(values[0]);
    if (attribute == null) {
        throw new IllegalArgumentException(
            "Colonne '" + values[0] + "' (" + columnData + ") introuvable depuis l'entité '" + root.getJavaType()
                + "'");
    }
    if (attribute.getPersistentAttributeType() == PersistentAttributeType.EMBEDDED) {
        // with @Embedded attribute
        return root.get(values[0]).get(values[1]);
    }
    From<?, ?> from = root;
    for (int i = 0; i < values.length - 1; i++) {

        Join<?, ?> join = null;
        for (final Join<?, ?> joinCandidate : from.getJoins()) {
            if (joinCandidate.getAttribute().getName().equals(values[i])) {
                // LOGGER.debug("Trouve joint d'entite: '{}'", values[i]);
                join = joinCandidate;
            }
        }
        if (join == null) {
            // LOGGER.debug("Joigant entite '{}'...", values[i]);
            join = from.join(values[i], JoinType.INNER);
        }
        from = join;
    }
    return from.get(values[values.length - 1]);
}
项目:jpasecurity    文件:EntityFilter.java   
private Path getSelectedEntityPath(Path selectedPath, Set<TypeDefinition> typeDefinitions) {
    if (!selectedPath.hasParentPath()) {
        return selectedPath;
    }
    Set<PersistentAttributeType> basicAttributeTypes = EnumSet.of(BASIC, EMBEDDED, ELEMENT_COLLECTION);
    Attribute<?, ?> attribute
        = Filter.attributeForPath(selectedPath).withMetamodel(metamodel).filter(typeDefinitions);
    while (selectedPath.hasParentPath() && basicAttributeTypes.contains(attribute.getPersistentAttributeType())) {
        selectedPath = selectedPath.getParentPath();
        attribute = Filter.attributeForPath(selectedPath).withMetamodel(metamodel).filter(typeDefinitions);
    }
    return selectedPath;
}
项目:olingo-odata2    文件:JPAEdmPropertyTest.java   
@Override
public PersistentAttributeType getPersistentAttributeType() {
  if (attributeName.equals("SOLITID")) {
    return PersistentAttributeType.BASIC;
  }
  return ATTRIBUTE_TYPE;
}
项目:olingo-odata2    文件:JPAEdmPropertyTest.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
private void setValuesToSet() {
  if (JPAEdmPropertyTest.ATTRIBUTE_TYPE.equals(PersistentAttributeType.BASIC)) {
    attributeSet.add((Attribute<? super String, String>) new JPAEdmAttribute(java.lang.String.class, "SOID"));
    attributeSet.add((Attribute<? super String, String>) new JPAEdmAttribute(java.lang.String.class, "SONAME"));
  } else if (JPAEdmPropertyTest.ATTRIBUTE_TYPE.equals(PersistentAttributeType.EMBEDDED)) {
    attributeSet.add(new JPAEdmAttribute(JPAEdmEmbeddable.class, ComplexType.ComplexTypeA.clazz.getName()));
  } else if (JPAEdmPropertyTest.ATTRIBUTE_TYPE.equals(PersistentAttributeType.MANY_TO_ONE)) {
    attributeSet.add(new JPAEdmPluralAttribute());
  }
}
项目:olingo-odata2    文件:JPAEdmPropertyTest.java   
@Override
public Member getJavaMember() {
  if (ATTRIBUTE_TYPE.equals(PersistentAttributeType.MANY_TO_ONE)) {
    return new JPAJavaMember();
  }
  return null;

}
项目:olingo-odata2    文件:JPAEdmPropertyTest.java   
@SuppressWarnings("unchecked")
@Override
public Class<String> getJavaType() {
  Class<?> clazz = null;
  if (ATTRIBUTE_TYPE.equals(PersistentAttributeType.BASIC)) {
    clazz = (Class<java.lang.String>) SimpleType.SimpleTypeA.clazz;
  } else {
    clazz = (Class<?>) ComplexType.ComplexTypeA.clazz;
  }
  return (Class<String>) clazz;
}
项目:query-utils    文件:EmbeddableUtil.java   
static boolean isCollectionOfEmbeddables(Attribute<?, ?> attribute) {
    logger.debug("isCollectionOfEmbeddables({})", attribute);
    boolean ret = attribute.getPersistentAttributeType() == PersistentAttributeType.ELEMENT_COLLECTION &&
           attribute instanceof PluralAttribute &&
           ((PluralAttribute<?,?,?>)attribute).getElementType().getPersistenceType() == PersistenceType.EMBEDDABLE;
    logger.debug("isCollectionOfEmbeddables -> {}", ret);
    return ret;
}
项目:jdal    文件:JpaUtils.java   
/**
 * Get all attributes where type or element type is assignable from class and has persistent type
 * @param type entity type
 * @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;
}
项目:jpasecurity    文件:EntityFilterTest.java   
@Before
public void initialize() throws ParseException, NoSuchMethodException {
    Metamodel metamodel = mock(Metamodel.class);
    SecurePersistenceUnitUtil persistenceUnitUtil = mock(SecurePersistenceUnitUtil.class);
    accessManager = mock(DefaultAccessManager.class);
    SecurityContext securityContext = mock(SecurityContext.class);
    EntityType entityType = mock(EntityType.class);
    SingularAttribute idAttribute = mock(SingularAttribute.class);
    SingularAttribute nameAttribute = mock(SingularAttribute.class);
    SingularAttribute parentAttribute = mock(SingularAttribute.class);
    PluralAttribute childrenAttribute = mock(PluralAttribute.class);
    MapAttribute relatedAttribute = mock(MapAttribute.class);
    Type integerType = mock(Type.class);
    when(metamodel.getEntities()).thenReturn(Collections.<EntityType<?>>singleton(entityType));
    when(metamodel.managedType(MethodAccessTestBean.class)).thenReturn(entityType);
    when(metamodel.entity(MethodAccessTestBean.class)).thenReturn(entityType);
    when(accessManager.getContext()).thenReturn(securityContext);
    when(securityContext.getAliases()).thenReturn(Collections.singleton(CURRENT_PRINCIPAL));
    when(securityContext.getAliasValue(CURRENT_PRINCIPAL)).thenReturn(NAME);
    when(entityType.getName()).thenReturn(MethodAccessTestBean.class.getSimpleName());
    when(entityType.getJavaType()).thenReturn((Class)MethodAccessTestBean.class);
    when(entityType.getAttributes()).thenReturn(new HashSet(Arrays.asList(
            idAttribute, nameAttribute, parentAttribute, childrenAttribute, relatedAttribute)));
    when(entityType.getAttribute("id")).thenReturn(idAttribute);
    when(entityType.getAttribute("name")).thenReturn(nameAttribute);
    when(entityType.getAttribute("parent")).thenReturn(parentAttribute);
    when(entityType.getAttribute("children")).thenReturn(childrenAttribute);
    when(entityType.getAttribute("related")).thenReturn(relatedAttribute);
    when(idAttribute.getName()).thenReturn("id");
    when(idAttribute.isCollection()).thenReturn(false);
    when(idAttribute.getType()).thenReturn(integerType);
    when(idAttribute.getPersistentAttributeType()).thenReturn(PersistentAttributeType.BASIC);
    when(idAttribute.getJavaType()).thenReturn(Integer.TYPE);
    when(idAttribute.getJavaMember()).thenReturn(MethodAccessTestBean.class.getDeclaredMethod("getId"));
    when(nameAttribute.getName()).thenReturn("name");
    when(nameAttribute.isCollection()).thenReturn(false);
    when(nameAttribute.getType()).thenReturn(integerType);
    when(nameAttribute.getPersistentAttributeType()).thenReturn(PersistentAttributeType.BASIC);
    when(nameAttribute.getJavaType()).thenReturn(String.class);
    when(nameAttribute.getJavaMember()).thenReturn(MethodAccessTestBean.class.getDeclaredMethod("getName"));
    when(parentAttribute.getName()).thenReturn("parent");
    when(parentAttribute.isCollection()).thenReturn(false);
    when(parentAttribute.getType()).thenReturn(entityType);
    when(parentAttribute.getPersistentAttributeType()).thenReturn(PersistentAttributeType.MANY_TO_ONE);
    when(parentAttribute.getJavaType()).thenReturn(MethodAccessTestBean.class);
    when(parentAttribute.getJavaMember()).thenReturn(MethodAccessTestBean.class.getDeclaredMethod("getParent"));
    when(childrenAttribute.getName()).thenReturn("children");
    when(childrenAttribute.isCollection()).thenReturn(true);
    when(childrenAttribute.getElementType()).thenReturn(entityType);
    when(childrenAttribute.getJavaMember())
        .thenReturn(MethodAccessTestBean.class.getDeclaredMethod("getChildren"));
    when(relatedAttribute.getName()).thenReturn("related");
    when(relatedAttribute.isCollection()).thenReturn(true);
    when(relatedAttribute.getKeyJavaType()).thenReturn(MethodAccessTestBean.class);
    when(relatedAttribute.getBindableJavaType()).thenReturn(MethodAccessTestBean.class);
    when(relatedAttribute.getElementType()).thenReturn(entityType);
    when(relatedAttribute.getJavaMember())
        .thenReturn(MethodAccessTestBean.class.getDeclaredMethod("getRelated"));

    entityFilter = new EntityFilter(metamodel, persistenceUnitUtil, initializeAccessRules(metamodel));
    DefaultAccessManager.Instance.register(accessManager);
}
项目:kc-rice    文件:EclipseLinkJpaMetadataProviderImpl.java   
/**
    * {@inheritDoc}
    */
@Override
protected void populateImplementationSpecificRelationshipLevelMetadata(DataObjectRelationshipImpl relationship,
        SingularAttribute<?, ?> rd) {
    // We need to go into the repository and grab the table name.
    Class<?> referencedClass = rd.getBindableJavaType();
    EntityType<?> referencedEntityType = entityManager.getMetamodel().entity(referencedClass);
    if (referencedEntityType instanceof EntityTypeImpl) {
        relationship
                .setBackingObjectName(((EntityTypeImpl<?>) referencedEntityType).getDescriptor().getTableName());
    }
    // Set to read only if store (save) operations should not be pushed through
    PersistentAttributeType persistentAttributeType = rd.getPersistentAttributeType();

    if (rd instanceof SingularAttributeImpl) {
        SingularAttributeImpl<?, ?> rel = (SingularAttributeImpl<?, ?>) rd;

        OneToOneMapping relationshipMapping = (OneToOneMapping) rel.getMapping();
        relationship.setReadOnly(relationshipMapping.isReadOnly());
        relationship.setSavedWithParent(relationshipMapping.isCascadePersist());
        relationship.setDeletedWithParent(relationshipMapping.isCascadeRemove());
        relationship.setLoadedAtParentLoadTime(relationshipMapping.isCascadeRefresh()
                && !relationshipMapping.isLazy());
        relationship.setLoadedDynamicallyUponUse(relationshipMapping.isCascadeRefresh()
                && relationshipMapping.isLazy());

        List<DataObjectAttributeRelationship> attributeRelationships = new ArrayList<DataObjectAttributeRelationship>();
        for (DatabaseField parentField : relationshipMapping.getForeignKeyFields()) {
            String parentFieldName = getPropertyNameFromDatabaseColumnName(rd.getDeclaringType(),
                    parentField.getName());
               if (parentFieldName != null) {
                DatabaseField childField = relationshipMapping.getSourceToTargetKeyFields().get(parentField);
                if (childField != null) {
                    // the target field is always done by column name. So, we need to get into the target entity and
                    // find the associated field :-(
                    // If the lookup fails, we will at least have the column name
                    String childFieldName = getPropertyNameFromDatabaseColumnName(referencedEntityType,
                               childField.getName());
                       if (childFieldName != null) {
                        attributeRelationships
                                   .add(new DataObjectAttributeRelationshipImpl(parentFieldName, childFieldName));
                       }
                } else {
                    LOG.warn("Unable to find child field reference.  There may be a JPA mapping problem on "
                            + rd.getDeclaringType().getJavaType() + ": " + relationship);
                }
               }
        }
        relationship.setAttributeRelationships(attributeRelationships);

           populateInverseRelationship(relationshipMapping, relationship);

    } else {
        // get what we can based on JPA values (note that we just set some to have values here)
        relationship.setReadOnly(persistentAttributeType == PersistentAttributeType.MANY_TO_ONE);
        relationship.setSavedWithParent(persistentAttributeType == PersistentAttributeType.ONE_TO_ONE);
        relationship.setDeletedWithParent(persistentAttributeType == PersistentAttributeType.ONE_TO_ONE);
        relationship.setLoadedAtParentLoadTime(true);
        relationship.setLoadedDynamicallyUponUse(false);
    }
}
项目:kc-rice    文件:JpaMetadataProviderImpl.java   
/**
 * Extracts the collection metadata from a single JPA {@link PluralAttribute} object.
    *
    * @param cd The plural attribute to process.
    * @return The collection metadata from a single JPA {@link PluralAttribute} object.
 */
protected DataObjectCollection getCollectionMetadataFromCollectionAttribute(PluralAttribute cd) {
    try {
        DataObjectCollectionImpl collection = new DataObjectCollectionImpl();

        // OJB stores the related class object name. We need to go into the repository and grab the table name.
        Class<?> collectionElementClass = cd.getElementType().getJavaType();
        EntityType<?> elementEntityType = entityManager.getMetamodel().entity(collectionElementClass);
        collection.setName(cd.getName());
        collection.setRelatedType(collectionElementClass);
        populateImplementationSpecificCollectionLevelMetadata(collection, cd);

        // Set to read only if store (save) operations should not be pushed through
        PersistentAttributeType persistentAttributeType = cd.getPersistentAttributeType();

        // default case:  Without any mapping attributes, collections are linked by their primary key
        if (persistentAttributeType == PersistentAttributeType.ONE_TO_MANY) {
            // TODO: We probably still need to handle the "mappedBy" property on the OneToMany definition

            // We only perform this logic here if we did not populate it in the implementation-specific call above
            if (collection.getAttributeRelationships().isEmpty()) {
                // need to obtain the keys for the relationship
                List<String> pkFields = getPrimaryKeyAttributeNames((EntityType<?>) cd.getDeclaringType());
                List<String> fkFields = getPrimaryKeyAttributeNames(elementEntityType);
                List<DataObjectAttributeRelationship> attributeRelationships = new ArrayList<DataObjectAttributeRelationship>();
                for (int i = 0; i < pkFields.size(); i++) {
                    attributeRelationships.add(new DataObjectAttributeRelationshipImpl(pkFields.get(i), fkFields
                            .get(i)));
                }
                collection.setAttributeRelationships(attributeRelationships);
            }
        } else if ( persistentAttributeType == PersistentAttributeType.MANY_TO_MANY ) {
            // OK, this is an assumption
            collection.setIndirectCollection( true );
            // And, since the connection is set at the *database* level through the @JoinTable anotation
            // we do not have any field names with which to make the connection
            collection.setAttributeRelationships(null);
        }

        return collection;
    } catch (RuntimeException ex) {
        LOG.error("Unable to process Collection metadata: " + cd);
        throw ex;
    }
}
项目:olingo-odata2    文件:JPAEdmPropertyTest.java   
@Override
public javax.persistence.metamodel.Attribute.PersistentAttributeType getPersistentAttributeType() {
  return ATTRIBUTE_TYPE;
}
项目:olingo-odata2    文件:JPAEdmPropertyTest.java   
@Override
public PersistentAttributeType getPersistentAttributeType() {
  return ATTRIBUTE_TYPE;
}
项目:breeze.server.java    文件:JPAMetadata.java   
/**
 * Adds an embeddable type definition
 * 
 * @param sattr - The embeddable type metamodel
 */
String addComponent(SingularAttribute sattr) {
    Class<?> type = sattr.getJavaType();

    // "Location:#com.breeze.model"
    String classKey = getEntityTypeName(type);
    if (_typeNames.contains(classKey)) {
        // Only add a complex type definition once.
        return classKey;
    }

    HashMap<String, Object> cmap = new LinkedHashMap<String, Object>();
    _typeList.add(0, cmap);
    _typeNames.add(classKey);

    cmap.put("shortName", type.getSimpleName());
    cmap.put("namespace", type.getPackage().getName());
    cmap.put("isComplexType", true);

    ArrayList<HashMap<String, Object>> dataArrayList = new ArrayList<HashMap<String, Object>>();
    cmap.put("dataProperties", dataArrayList);

    EmbeddableType<?> bed = _emFactory.getMetamodel().embeddable(type);

    for (Attribute<?,?> attrib : bed.getAttributes()) {
        PersistentAttributeType attrType = attrib.getPersistentAttributeType();
        if (!(attrib instanceof SingularAttribute)) {
            throw new RuntimeException("Collections not supported in complex types");
        }
        SingularAttribute cattr = (SingularAttribute) attrib; 
        if (attrType == PersistentAttributeType.EMBEDDED) {
            // nested complex type
            String complexTypeName = addComponent(cattr);
            HashMap<String, Object> compMap = new HashMap<String, Object>();
            compMap.put("nameOnServer", attrib.getName());
            compMap.put("complexTypeName", complexTypeName);
            compMap.put("isNullable", cattr.isOptional());
            dataArrayList.add(compMap);
        } else {
            // data property
            HashMap<String, Object> dmap = makeDataProperty(cattr.getName(), cattr, false, false);
            dataArrayList.add(dmap);
        }
    }

    return classKey;
}
项目:rice    文件:EclipseLinkJpaMetadataProviderImpl.java   
/**
    * {@inheritDoc}
    */
@Override
protected void populateImplementationSpecificRelationshipLevelMetadata(DataObjectRelationshipImpl relationship,
        SingularAttribute<?, ?> rd) {
    // We need to go into the repository and grab the table name.
    Class<?> referencedClass = rd.getBindableJavaType();
    EntityType<?> referencedEntityType = entityManager.getMetamodel().entity(referencedClass);
    if (referencedEntityType instanceof EntityTypeImpl) {
        relationship
                .setBackingObjectName(((EntityTypeImpl<?>) referencedEntityType).getDescriptor().getTableName());
    }
    // Set to read only if store (save) operations should not be pushed through
    PersistentAttributeType persistentAttributeType = rd.getPersistentAttributeType();

    if (rd instanceof SingularAttributeImpl) {
        SingularAttributeImpl<?, ?> rel = (SingularAttributeImpl<?, ?>) rd;

        OneToOneMapping relationshipMapping = (OneToOneMapping) rel.getMapping();
        relationship.setReadOnly(relationshipMapping.isReadOnly());
        relationship.setSavedWithParent(relationshipMapping.isCascadePersist());
        relationship.setDeletedWithParent(relationshipMapping.isCascadeRemove());
        relationship.setLoadedAtParentLoadTime(relationshipMapping.isCascadeRefresh()
                && !relationshipMapping.isLazy());
        relationship.setLoadedDynamicallyUponUse(relationshipMapping.isCascadeRefresh()
                && relationshipMapping.isLazy());

           List<DataObjectAttributeRelationship> attributeRelationships = new ArrayList<DataObjectAttributeRelationship>();
           List<String> referencedEntityPkFields = getPrimaryKeyAttributeNames(referencedEntityType);

           for (String referencedEntityPkField : referencedEntityPkFields) {
               for (Map.Entry<DatabaseField, DatabaseField> entry :
                       relationshipMapping.getTargetToSourceKeyFields().entrySet()) {
                   DatabaseField childDatabaseField = entry.getKey();
                   String childFieldName = getPropertyNameFromDatabaseColumnName(referencedEntityType,
                           childDatabaseField.getName());

                   if (referencedEntityPkField.equalsIgnoreCase(childFieldName)) {
                       DatabaseField parentDatabaseField = entry.getValue();
                       String parentFieldName = getPropertyNameFromDatabaseColumnName(rd.getDeclaringType(),
                               parentDatabaseField.getName());

                       if (parentFieldName != null) {
                           attributeRelationships
                                   .add(new DataObjectAttributeRelationshipImpl(parentFieldName, childFieldName));
                           break;
                       } else {
                           LOG.warn("Unable to find parent field reference.  There may be a JPA mapping problem on " +
                                   referencedEntityType.getJavaType() + ": " + relationship);
                       }
                   }
               }
           }

           relationship.setAttributeRelationships(attributeRelationships);

           populateInverseRelationship(relationshipMapping, relationship);

    } else {
        // get what we can based on JPA values (note that we just set some to have values here)
        relationship.setReadOnly(persistentAttributeType == PersistentAttributeType.MANY_TO_ONE);
        relationship.setSavedWithParent(persistentAttributeType == PersistentAttributeType.ONE_TO_ONE);
        relationship.setDeletedWithParent(persistentAttributeType == PersistentAttributeType.ONE_TO_ONE);
        relationship.setLoadedAtParentLoadTime(true);
        relationship.setLoadedDynamicallyUponUse(false);
    }
}
项目:rice    文件:JpaMetadataProviderImpl.java   
/**
 * Extracts the collection metadata from a single JPA {@link PluralAttribute} object.
    *
    * @param cd The plural attribute to process.
    * @return The collection metadata from a single JPA {@link PluralAttribute} object.
 */
protected DataObjectCollection getCollectionMetadataFromCollectionAttribute(PluralAttribute cd) {
    try {
        DataObjectCollectionImpl collection = new DataObjectCollectionImpl();

        // OJB stores the related class object name. We need to go into the repository and grab the table name.
        Class<?> collectionElementClass = cd.getElementType().getJavaType();
        EntityType<?> elementEntityType = entityManager.getMetamodel().entity(collectionElementClass);
        collection.setName(cd.getName());
        collection.setRelatedType(collectionElementClass);
        populateImplementationSpecificCollectionLevelMetadata(collection, cd);

        // Set to read only if store (save) operations should not be pushed through
        PersistentAttributeType persistentAttributeType = cd.getPersistentAttributeType();

        // default case:  Without any mapping attributes, collections are linked by their primary key
        if (persistentAttributeType == PersistentAttributeType.ONE_TO_MANY) {
            // TODO: We probably still need to handle the "mappedBy" property on the OneToMany definition

            // We only perform this logic here if we did not populate it in the implementation-specific call above
            if (collection.getAttributeRelationships().isEmpty()) {
                // need to obtain the keys for the relationship
                List<String> pkFields = getPrimaryKeyAttributeNames((EntityType<?>) cd.getDeclaringType());
                List<String> fkFields = getPrimaryKeyAttributeNames(elementEntityType);
                List<DataObjectAttributeRelationship> attributeRelationships = new ArrayList<DataObjectAttributeRelationship>();
                for (int i = 0; i < pkFields.size(); i++) {
                    attributeRelationships.add(new DataObjectAttributeRelationshipImpl(pkFields.get(i), fkFields
                            .get(i)));
                }
                collection.setAttributeRelationships(attributeRelationships);
            }
        } else if ( persistentAttributeType == PersistentAttributeType.MANY_TO_MANY ) {
            // OK, this is an assumption
            collection.setIndirectCollection( true );
            // And, since the connection is set at the *database* level through the @JoinTable anotation
            // we do not have any field names with which to make the connection
            collection.setAttributeRelationships(null);
        }

        return collection;
    } catch (RuntimeException ex) {
        LOG.error("Unable to process Collection metadata: " + cd);
        throw ex;
    }
}
项目:jdal    文件:JpaDao.java   
/**
 * Null References on one to many and one to one associations.
 * Will only work if association has annotated with a mappedBy attribute.
 * 
 * @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);
                    }
                }
            }
        }
    }
}
项目:jdal    文件:JpaUtils.java   
/**
 * Get all attributes of type by persistent type
 * @param type 
 * @param persistentType
 * @return a set with all attributes of type with persistent type persistentType.
 */
public static Set<Attribute<?, ?>> getAttributes(EntityType<?> type, PersistentAttributeType persistentType) {
    return getAttributes(type, persistentType, Object.class);
}