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

项目:bootstrap    文件:CsvForJpa.java   
/**
 * Return JPA managed properties.
 * 
 * @param <T>
 *            Bean type.
 * @param beanType
 *            the bean type.
 * @return the headers built from given type.
 */
public <T> String[] getJpaHeaders(final Class<T> beanType) {
    // Build descriptor list respecting the declaration order
    final OrderedFieldCallback fieldCallBack = new OrderedFieldCallback();
    ReflectionUtils.doWithFields(beanType, fieldCallBack);
    final List<String> orderedDescriptors = fieldCallBack.descriptorsOrdered;

    // Now filter the properties
    final List<String> descriptorsFiltered = new ArrayList<>();
    final ManagedType<T> managedType = transactionManager.getEntityManagerFactory().getMetamodel().managedType(beanType);
    for (final String propertyDescriptor : orderedDescriptors) {
        for (final Attribute<?, ?> attribute : managedType.getAttributes()) {
            // Match only basic attributes
            if (attribute instanceof SingularAttribute<?, ?> && propertyDescriptor.equals(attribute.getName())) {
                descriptorsFiltered.add(attribute.getName());
                break;
            }
        }
    }

    // Initialize the CSV reader
    return descriptorsFiltered.toArray(new String[descriptorsFiltered.size()]);
}
项目:bootstrap    文件:CsvForJpa.java   
/**
 * Delete the managed entities. Self referencing rows are set to NULL before the deletion.
 * 
 * @param beanTypes
 *            the ordered set to clean.
 */
public void cleanup(final Class<?>... beanTypes) {

    // Clean the data
    for (int i = beanTypes.length; i-- > 0;) {
        final Class<?> entityClass = beanTypes[i];
        final String update = em.getMetamodel().managedType(entityClass).getAttributes().stream().filter(a -> a.getJavaType().equals(entityClass))
                .map(Attribute::getName).map(name -> name + "=NULL").collect(Collectors.joining(", "));
        if (update.length() > 0) {
            // Clear the self referencing rows
            em.createQuery("UPDATE " + entityClass.getName() + " SET " + update).executeUpdate();
        }
        em.createQuery("DELETE FROM " + entityClass.getName()).executeUpdate();
    }
    em.flush();
}
项目:rpb    文件:ByPatternUtil.java   
/**
 * Lookup entities having at least one String attribute matching the passed sp's pattern
 */
@SuppressWarnings("unused")
public <T> Predicate byPattern(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder, final SearchParameters sp, final Class<T> type) {
    if (!sp.hasSearchPattern()) {
        return null;
    }

    List<Predicate> predicates = newArrayList();
    EntityType<T> entity = em.getMetamodel().entity(type);
    String pattern = sp.getSearchPattern();

    for (Attribute<T, ?> attr : entity.getDeclaredSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) {
            continue;
        }

        if (attr.getJavaType() == String.class) {
            predicates.add(JpaUtil.stringPredicate(root.get(attribute(entity, attr)), pattern, sp, builder));
        }
    }

    return JpaUtil.orPredicate(builder, predicates);
}
项目:jpasecurity    文件:TypeDefinition.java   
public Attribute<?, ?> filter() {
    Type<?> type = forModel(metamodel).filter(rootType);
    Attribute<?, ?> result = null;
    for (int i = 1; i < pathElements.length; i++) {
        if (!(type instanceof ManagedType)) {
            throw new PersistenceException("Cannot navigate through simple property "
                    + pathElements[i] + " of type " + type.getJavaType());
        }
        result = ((ManagedType<?>)type).getAttribute(pathElements[i]);
        if (result.isCollection()) {
            type = ((PluralAttribute<?, ?, ?>)result).getElementType();
        } else {
            type = ((SingularAttribute<?, ?>)result).getType();
        }
    }
    return result;
}
项目:jpasecurity    文件:MappingEvaluator.java   
public boolean visit(JpqlPath node, Set<TypeDefinition> typeDefinitions) {
    Alias alias = new Alias(node.jjtGetChild(0).getValue());
    Class<?> type = getType(alias, typeDefinitions);
    for (int i = 1; i < node.jjtGetNumChildren(); i++) {
        ManagedType<?> managedType = forModel(metamodel).filter(type);
        String attributeName = node.jjtGetChild(i).getValue();
        Attribute<?, ?> attribute = managedType.getAttribute(attributeName);
        if (attribute instanceof SingularAttribute
            && ((SingularAttribute<?, ?>)attribute).getType().getPersistenceType() == PersistenceType.BASIC
            && i < node.jjtGetNumChildren() - 1) {
            String error = "Cannot navigate through simple property "
                    + attributeName + " in class " + type.getName();
            throw new PersistenceException(error);
        }
        type = attribute.getJavaType();
    }
    return false;
}
项目: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());
    }
}
项目:invesdwin-context-persistence    文件:NativeJdbcIndexCreationHandler.java   
@Transactional
private void dropIndexNewTx(final Class<?> entityClass, final Index index, final EntityManager em,
        final UniqueNameGenerator uniqueNameGenerator) {
    Assertions.assertThat(index.columnNames().length).isGreaterThan(0);
    final String comma = ", ";
    final String name;
    if (Strings.isNotBlank(index.name())) {
        name = index.name();
    } else {
        name = "idx" + entityClass.getSimpleName();
    }
    final StringBuilder cols = new StringBuilder();
    final ManagedType<?> managedType = em.getMetamodel().managedType(entityClass);
    for (final String columnName : index.columnNames()) {
        if (cols.length() > 0) {
            cols.append(comma);
        }
        final Attribute<?, ?> column = Attributes.findAttribute(managedType, columnName);
        cols.append(Attributes.extractNativeSqlColumnName(column));
    }

    final String create = "DROP INDEX " + uniqueNameGenerator.get(name) + " ON " + entityClass.getSimpleName();
    em.createNativeQuery(create).executeUpdate();
}
项目:OpenCyclos    文件:JpaQueryHandler.java   
/**
 * Copies the persistent properties from the source to the destination entity
 */
public void copyProperties(final Entity source, final Entity dest) {
    if (source == null || dest == null) {
        return;
    }

    final ManagedType<?> metaData = getClassMetamodel(source);
    for (Attribute<?, ?> attribute : metaData.getAttributes()) {
        // Skip the collections
        if (attribute.isCollection()) {
            PropertyHelper.set(dest, attribute.getName(), null);
        } else {
            PropertyHelper.set(dest, attribute.getName(), PropertyHelper.get(source, attribute.getName()));
        }
    }

}
项目:owsi-core-parent    文件:AbstractTestCase.java   
/**
 * Méthode permettant de s'assurer que les attributs des classes marquées @Entity ne seront pas sérialisés en
 * "bytea" lors de leur écriture en base.
 * 
 * @param classesAutorisees : concerne uniquement des classes matérialisées. Si une enum fait péter le test, c'est
 * qu'il manque l'annotation @Enumerated ou que celle-ci prend EnumType.ORDINAL en paramètre
 */
protected void testMetaModel(List<Attribute<?, ?>> ignoredAttributes, Class<?>... classesAutorisees) throws NoSuchFieldException, SecurityException {
    List<Class<?>> listeAutorisee = Lists.newArrayList();
    listeAutorisee.add(String.class);
    listeAutorisee.add(Long.class);
    listeAutorisee.add(Double.class);
    listeAutorisee.add(Integer.class);
    listeAutorisee.add(Float.class);
    listeAutorisee.add(Date.class);
    listeAutorisee.add(BigDecimal.class);
    listeAutorisee.add(Boolean.class);
    listeAutorisee.add(int.class);
    listeAutorisee.add(long.class);
    listeAutorisee.add(double.class);
    listeAutorisee.add(boolean.class);
    listeAutorisee.add(float.class);
    for (Class<?> clazz : classesAutorisees) {
        listeAutorisee.add(clazz);
    }

    for (EntityType<?> entityType : getEntityManager().getMetamodel().getEntities()) {
        for (Attribute<?, ?> attribute : entityType.getDeclaredAttributes()) {
            testMetaModel(attribute, listeAutorisee, ignoredAttributes);
        }
    }
}
项目:rpb    文件:ByPatternUtil.java   
/**
 * Lookup entities having at least one String attribute matching the passed sp's pattern
 */
@SuppressWarnings("unused")
public <T> Predicate byPattern(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder, final SearchParameters sp, final Class<T> type) {
    if (!sp.hasSearchPattern()) {
        return null;
    }

    List<Predicate> predicates = newArrayList();
    EntityType<T> entity = em.getMetamodel().entity(type);
    String pattern = sp.getSearchPattern();

    for (Attribute<T, ?> attr : entity.getDeclaredSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) {
            continue;
        }

        if (attr.getJavaType() == String.class) {
            predicates.add(JpaUtil.stringPredicate(root.get(attribute(entity, attr)), pattern, sp, builder));
        }
    }

    return JpaUtil.orPredicate(builder, predicates);
}
项目:random-jpa    文件:AttributeHelperTest.java   
@Test
public void shouldReturnListOfFieldsForAtttributes() throws Exception {

    EntityManagerProvider.init();

    final List<Attribute<?, ?>> attributes = new ArrayList<Attribute<?, ?>>();
    attributes.add(A_.id);
    attributes.add(B_.id);

    final List<Field> fields = AttributeHelper.getFields(attributes);

    Assert.assertEquals(2, fields.size());
    Assert.assertEquals("id", fields.get(0).getName());
    Assert.assertEquals(A.class, fields.get(0).getDeclaringClass());

    Assert.assertEquals("id", fields.get(1).getName());
    Assert.assertEquals(B.class, fields.get(1).getDeclaringClass());
}
项目:actionbazaar    文件:ItemManager.java   
public void printPersistenceModel() {
    Metamodel metaModel = entityManager.getMetamodel();
    Set<EntityType<? extends Object>> types = metaModel.getEntities();
    for(EntityType<? extends Object> type : types) {
        logger.log(Level.INFO, "--> Type: {0}", type);
        Set attributes = type.getAttributes();
        for(Object obj : attributes) {
            logger.log(Level.INFO, "Name: {0}", ((Attribute)obj).getName());
            logger.log(Level.INFO, "isCollection: {0}", ((Attribute)obj).isCollection());
            logger.log(Level.INFO, "Name: {0}", ((Attribute)obj).isAssociation());
            logger.log(Level.INFO, "Name: {0}", ((Attribute)obj).getPersistentAttributeType());
        }

    }

    EntityType<Item> item = metaModel.entity(Item.class);
}
项目:jittrackGTS    文件:SpecificationHelper.java   
private static boolean isPathJoin(Path<?> path) {
    //todo how to avoid this?
    /*
    if (path instanceof PluralAttributePath) {
        return true;
    }
    */
    if (Collection.class.isAssignableFrom(path.getJavaType()) || path.getJavaType().isArray()) {
        return true;
    }
    Attribute.PersistentAttributeType persistentAttributeType = null;
    if (path.getModel() instanceof SingularAttribute) {
        persistentAttributeType = ((SingularAttribute) path.getModel()).getPersistentAttributeType();
    }
    if (persistentAttributeType == Attribute.PersistentAttributeType.MANY_TO_MANY ||
        persistentAttributeType == Attribute.PersistentAttributeType.MANY_TO_ONE ||
        persistentAttributeType == Attribute.PersistentAttributeType.ONE_TO_MANY ||
        persistentAttributeType == Attribute.PersistentAttributeType.ONE_TO_ONE) {
        return true;
    }
    return false;
}
项目:javaee-lab    文件:MetamodelUtil.java   
public List<Attribute<?, ?>> toAttributes(String path, Class<?> from) {
    try {
        List<Attribute<?, ?>> attributes = newArrayList();
        Class<?> current = from;
        for (String pathItem : Splitter.on(".").split(path)) {
            Class<?> metamodelClass = getCachedClass(current);
            Field field = metamodelClass.getField(pathItem);
            Attribute<?, ?> attribute = (Attribute<?, ?>) field.get(null);
            attributes.add(attribute);
            if (attribute instanceof PluralAttribute) {
                current = ((PluralAttribute<?, ?, ?>) attribute).getElementType().getJavaType();
            } else {
                current = attribute.getJavaType();
            }
        }
        return attributes;
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}
项目:javaee-lab    文件:JpaUtil.java   
@SuppressWarnings("unchecked")
public <E, F> Path<F> getPath(Root<E> root, List<Attribute<?, ?>> attributes) {
    Path<?> path = root;
    for (Attribute<?, ?> attribute : attributes) {
        boolean found = false;
        if (path instanceof FetchParent) {
            for (Fetch<E, ?> fetch : ((FetchParent<?, E>) path).getFetches()) {
                if (attribute.getName().equals(fetch.getAttribute().getName()) && (fetch instanceof Join<?, ?>)) {
                    path = (Join<E, ?>) fetch;
                    found = true;
                    break;
                }
            }
        }
        if (!found) {
            if (attribute instanceof PluralAttribute) {
                path = ((From<?, ?>) path).join(attribute.getName(), JoinType.LEFT);
            } else {
                path = path.get(attribute.getName());
            }
        }
    }
    return (Path<F>) path;
}
项目:javaee-lab    文件:JpaUtil.java   
public void verifyPath(List<Attribute<?, ?>> path) {
    List<Attribute<?, ?>> attributes = newArrayList(path);
    Class<?> from = null;
    if (attributes.get(0).isCollection()) {
        from = ((PluralAttribute) attributes.get(0)).getElementType().getJavaType();
    } else {
        from = attributes.get(0).getJavaType();
    }
    attributes.remove(0);
    for (Attribute<?, ?> attribute : attributes) {
        if (!attribute.getDeclaringType().getJavaType().isAssignableFrom(from)) {
            throw new IllegalStateException("Wrong path.");
        }
        from = attribute.getJavaType();
    }
}
项目:javaee-lab    文件:GenericRepository.java   
@SuppressWarnings({"unchecked", "rawtypes"})
protected void fetches(SearchParameters sp, Root<E> root) {
    for (List<Attribute<?, ?>> args : sp.getFetches()) {
        FetchParent<?, ?> from = root;
        for (Attribute<?, ?> arg : args) {
            boolean found = false;
            for (Fetch<?, ?> fetch : from.getFetches()) {
                if (arg.equals(fetch.getAttribute())) {
                    from = fetch;
                    found = true;
                    break;
                }
            }
            if (!found) {
                if (arg instanceof PluralAttribute) {
                    from = from.fetch((PluralAttribute) arg, JoinType.LEFT);
                } else {
                    from = from.fetch((SingularAttribute) arg, JoinType.LEFT);
                }
            }
        }
    }
}
项目:crnk-framework    文件:QueryUtil.java   
private static boolean containsMultiRelationFetch(Set<?> fetches) {
    for (Object fetchObj : fetches) {
        Fetch<?, ?> fetch = (Fetch<?, ?>) fetchObj;

        Attribute<?, ?> attr = fetch.getAttribute();
        if (attr.isAssociation() && attr.isCollection())
            return true;

        if (containsMultiRelationFetch(fetch.getFetches()))
            return true;
    }
    return false;
}
项目:crnk-framework    文件:QueryUtil.java   
private static boolean containsMultiRelationJoin(Set<?> fetches) {
    for (Object fetchObj : fetches) {
        Fetch<?, ?> fetch = (Fetch<?, ?>) fetchObj;
        Attribute<?, ?> attr = fetch.getAttribute();
        if (attr.isAssociation() && attr.isCollection())
            return true;

        if (containsMultiRelationFetch(fetch.getFetches()))
            return true;
    }
    return false;
}
项目:bootstrap    文件:AbstractSpecification.java   
/**
 * Retrieve an existing join within the ones within the given root and that match to given attribute.
 * 
 * @param from
 *            the from source element.
 * @param attribute
 *            the attribute to join
 * @return The join/fetch path if it exists.
 * @param <U>
 *            The source type of the {@link Join}
 */
@SuppressWarnings("unchecked")
protected <U, T> PathImplementor<T> getJoinPath(final From<?, U> from, final Attribute<?, ?> attribute) {

    // Search within current joins
    for (final Join<U, ?> join : from.getJoins()) {
        if (join.getAttribute().equals(attribute)) {
            return fixAlias((Join<U, T>) join, aliasCounter);
        }
    }
    return null;
}
项目: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]);
}
项目:rpb    文件:ByExampleUtil.java   
private <T> Object getValue(T example, Attribute<? super T, ?> attr) {
    try {
        return ReflectionUtils.invokeMethod((Method) attr.getJavaMember(), example);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}
项目:katharsis-framework    文件:QueryUtil.java   
private static boolean containsMultiRelationFetch(Set<?> fetches) {
  for (Object fetchObj : fetches) {
    Fetch<?, ?> fetch = (Fetch<?, ?>) fetchObj;

    Attribute<?, ?> attr = fetch.getAttribute();
    if (attr.isAssociation() && attr.isCollection())
      return true;

    if (containsMultiRelationFetch(fetch.getFetches()))
      return true;
  }
  return false;
}
项目:katharsis-framework    文件:QueryUtil.java   
private static boolean containsMultiRelationJoin(Set<?> fetches) {
  for (Object fetchObj : fetches) {
    Fetch<?, ?> fetch = (Fetch<?, ?>) fetchObj;
    Attribute<?, ?> attr = fetch.getAttribute();
    if (attr.isAssociation() && attr.isCollection())
      return true;

    if (containsMultiRelationFetch(fetch.getFetches()))
      return true;
  }
  return false;
}
项目: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;
}
项目:jpasecurity    文件:TypeDefinition.java   
@Override
protected ManagedType<?> transform(TypeDefinition typeDefinition) {
    if (!path.hasSubpath()) {
        return forModel(metamodel).filter(typeDefinition.getType());
    }
    Attribute<?, ?> attribute = (Attribute<?, ?>)filter.transform(typeDefinition);
    if (attribute.isCollection()) {
        return (ManagedType<?>)((PluralAttribute<?, ?, ?>)attribute).getElementType();
    } else {
        return (ManagedType<?>)((SingularAttribute<?, ?>)attribute).getType();
    }
}
项目:jpasecurity    文件:MappedPathEvaluator.java   
public <R> List<R> evaluateAll(final Collection<?> root, String path) {
    String[] pathElements = path.split("\\.");
    List<Object> rootCollection = new ArrayList<Object>(root);
    List<R> resultCollection = new ArrayList<R>();
    for (String property: pathElements) {
        resultCollection.clear();
        for (Object rootObject: rootCollection) {
            if (rootObject == null) {
                continue;
            }
            ManagedType<?> managedType = forModel(metamodel).filter(rootObject.getClass());
            if (containsAttribute(managedType, property)) {
                Attribute<?, ?> propertyMapping = managedType.getAttribute(property);
                Object result = getValue(rootObject, propertyMapping);
                if (result instanceof Collection) {
                    resultCollection.addAll((Collection<R>)result);
                } else if (result != null) {
                    resultCollection.add((R)result);
                }
            } // else the property may be of a subclass and this path is ruled out by inner join on subclass table
        }
        rootCollection.clear();
        for (Object resultObject: resultCollection) {
            if (resultObject instanceof Collection) {
                rootCollection.addAll((Collection<Object>)resultObject);
            } else {
                rootCollection.add(resultObject);
            }
        }
    }
    return resultCollection;
}
项目:jpasecurity    文件:MappedPathEvaluator.java   
private boolean containsAttribute(ManagedType<?> managedType, String name) {
    for (Attribute<?, ?> attributes : managedType.getAttributes()) {
        if (attributes.getName().equals(name)) {
            return true;
        }
    }
    return false;
}
项目:jpasecurity    文件:JpqlCompiler.java   
private boolean visitJoin(Node node,
                          Set<TypeDefinition> typeDefinitions,
                          boolean innerJoin,
                          boolean fetchJoin) {
    Path fetchPath = new Path(node.jjtGetChild(0).toString());
    Class<?> keyType = null;
    Attribute<?, ?> attribute = TypeDefinition.Filter.attributeForPath(fetchPath)
            .withMetamodel(metamodel)
            .filter(typeDefinitions);
    Class<?> type;
    if (attribute instanceof MapAttribute) {
        MapAttribute<?, ?, ?> mapAttribute = (MapAttribute<?, ?, ?>)attribute;
        keyType = mapAttribute.getKeyJavaType();
        type = mapAttribute.getBindableJavaType();
    } else {
        type = TypeDefinition.Filter.managedTypeForPath(fetchPath)
                .withMetamodel(metamodel)
                .filter(typeDefinitions)
                .getJavaType();
    }
    if (keyType != null) {
        typeDefinitions.add(new TypeDefinition(keyType, fetchPath, innerJoin, fetchJoin));
    }
    if (node.jjtGetNumChildren() == 1) {
        typeDefinitions.add(new TypeDefinition(type, fetchPath, innerJoin, fetchJoin));
    } else {
        Alias alias = getAlias(node);
        typeDefinitions.add(new TypeDefinition(alias, type, fetchPath, innerJoin, fetchJoin));
    }
    return false;
}
项目:jpasecurity    文件:CriteriaEntityFilter.java   
private String getName(Bindable<?> bindable) {
    if (bindable.getBindableType() == BindableType.ENTITY_TYPE) {
        EntityType<?> entityType = (EntityType<?>)bindable;
        return entityType.getName();
    } else {
        Attribute<?, ?> attribute = (Attribute<?, ?>)bindable;
        return attribute.getName();
    }
}
项目:jpasecurity    文件:AclValueIteratorTest.java   
private MappedPathEvaluator createPathEvaluator() throws NoSuchFieldException {
    Metamodel metamodel = mock(Metamodel.class);
    SecurePersistenceUnitUtil persistenceUnitUtil = mock(SecurePersistenceUnitUtil.class);
    EntityType userType = mock(EntityType.class);
    EntityType groupType = mock(EntityType.class);
    Attribute groupsAttribute = mock(Attribute.class);
    Attribute fullHierarchyAttribute = mock(Attribute.class);
    when(metamodel.managedType(User.class)).thenReturn(userType);
    when(metamodel.managedType(Group.class)).thenReturn(groupType);
    when(persistenceUnitUtil.isLoaded(any())).thenReturn(true);
    when(persistenceUnitUtil.initialize(any())).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return invocation.getArgument(0);
        }
    });
    when(userType.getAttributes()).thenReturn(Collections.singleton(groupsAttribute));
    when(userType.getAttribute("groups")).thenReturn(groupsAttribute);
    when(groupType.getAttributes()).thenReturn(Collections.singleton(fullHierarchyAttribute));
    when(groupType.getAttribute("fullHierarchy")).thenReturn(fullHierarchyAttribute);
    when(groupsAttribute.getName()).thenReturn("groups");
    when(groupsAttribute.getJavaMember()).thenReturn(User.class.getDeclaredField("groups"));
    when(fullHierarchyAttribute.getName()).thenReturn("fullHierarchy");
    when(fullHierarchyAttribute.getJavaMember())
        .thenReturn(Group.class.getDeclaredField("fullHierarchy"));
    return new MappedPathEvaluator(metamodel, persistenceUnitUtil);
}
项目:invesdwin-context-persistence    文件:QueryByExampleHelper.java   
/**
 * When and=false, all criteria are combined with OR, else AND is used.
 * 
 * @see <a href="http://stackoverflow.com/questions/2880209/jpa-findbyexample">Source</a>
 */
public TypedQuery<E> queryByExample(final String persistenceUnitName, final EntityManager em,
        final Class<E> genericType, final E example, final boolean and, final QueryConfig config) {
    assertEntityExampleWithoutId(example);
    final CriteriaBuilder cb = em.getCriteriaBuilder();
    final CriteriaQuery<E> cq = cb.createQuery(genericType);
    final Root<E> r = cq.from(genericType);
    Predicate p = cb.conjunction();
    final EntityType<E> et = em.getMetamodel().entity(genericType);
    final Set<Attribute<? super E, ?>> attrs = et.getAttributes();
    boolean firstField = true;
    for (final Attribute<? super E, ?> attr : attrs) {
        final String name = attr.getName();
        final String javaName = attr.getJavaMember().getName();
        final Field f = Reflections.findField(genericType, javaName);
        Reflections.makeAccessible(f);
        final Object value = Reflections.getField(f, example);
        if (value != null) {
            final Predicate pred = cb.equal(r.get(name), value);
            if (and || firstField) {
                p = cb.and(p, pred);
            } else {
                p = cb.or(p, pred);
            }
            firstField = false;
        }
    }
    cq.select(r).where(p);
    final TypedQuery<E> query = em.createQuery(cq);
    QueryConfig.configure(persistenceUnitName, query, config);
    return query;
}
项目:invesdwin-context-persistence    文件:QueryByExampleHelper.java   
private Query xByExample(final EntityManager em, final String queryStart, final Class<E> genericType,
        final E example, final boolean and) {
    assertEntityExampleWithoutId(example);
    final StringBuilder sb = new StringBuilder(queryStart);
    sb.append(" FROM ");
    sb.append(extractEntityName(genericType));
    sb.append(" e WHERE 1 = 1");
    final Map<String, Object> params = new HashMap<String, Object>();
    final EntityType<E> et = em.getMetamodel().entity(genericType);
    final Set<Attribute<? super E, ?>> attrs = et.getAttributes();
    boolean firstField = true;
    for (final Attribute<? super E, ?> attr : attrs) {
        final String name = attr.getName();
        final String javaName = attr.getJavaMember().getName();
        final Field f = Reflections.findField(genericType, javaName);
        Reflections.makeAccessible(f);
        final Object value = Reflections.getField(f, example);
        if (value != null) {
            params.put(name, value);
            if (and || firstField) {
                sb.append(" AND ");
            } else {
                sb.append(" OR ");
            }
            sb.append("e.");
            sb.append(name);
            sb.append(" = :");
            sb.append(name);
            firstField = false;
        }
    }
    final Query query = em.createQuery(sb.toString());
    for (final Entry<String, Object> param : params.entrySet()) {
        query.setParameter(param.getKey(), param.getValue());
    }
    return query;
}
项目:invesdwin-context-persistence    文件:MySqlLoadDataInfile.java   
@SuppressWarnings("unchecked")
private List<String> determineJavaColumnNames(final PersistenceUnitContext puContext) {
    final List<String> javaColumnNames = new ArrayList<String>();
    final EntityManager em = puContext.getEntityManager();
    final EntityType<E> et = (EntityType<E>) em.getMetamodel().entity(genericType);
    final Set<Attribute<? super E, ?>> attrs = et.getAttributes();
    for (final Attribute<? super E, ?> attr : attrs) {
        final String javaName = attr.getJavaMember().getName();
        javaColumnNames.add(javaName);
    }
    return javaColumnNames;
}
项目:invesdwin-context-persistence    文件:Attributes.java   
public static Attribute<?, ?> findAttribute(final ManagedType<?> managedType, final String columnName) {
    try {
        return managedType.getAttribute(Strings.removeEnd(columnName, Attributes.ID_SUFFIX));
    } catch (final IllegalArgumentException e) {
        return managedType.getAttribute(columnName);
    }
}
项目:invesdwin-context-persistence    文件:NativeJdbcIndexCreationHandler.java   
@Transactional
private void createIndexNewTx(final Class<?> entityClass, final Index index, final EntityManager em,
        final UniqueNameGenerator uniqueNameGenerator) {
    Assertions.assertThat(index.columnNames().length).isGreaterThan(0);
    final String comma = ", ";
    final String name;
    if (Strings.isNotBlank(index.name())) {
        name = index.name();
    } else {
        name = "idx" + entityClass.getSimpleName();
    }
    final StringBuilder cols = new StringBuilder();
    final ManagedType<?> managedType = em.getMetamodel().managedType(entityClass);
    for (final String columnName : index.columnNames()) {
        if (cols.length() > 0) {
            cols.append(comma);
        }
        final Attribute<?, ?> column = Attributes.findAttribute(managedType, columnName);
        cols.append(Attributes.extractNativeSqlColumnName(column));
    }

    final String unique;
    if (index.unique()) {
        unique = " UNIQUE";
    } else {
        unique = "";
    }

    final String create = "CREATE" + unique + " INDEX " + uniqueNameGenerator.get(name) + " ON "
            + entityClass.getSimpleName() + " ( " + cols + " )";
    em.createNativeQuery(create).executeUpdate();
}
项目:OpenCyclos    文件:JpaQueryHandler.java   
@SuppressWarnings("unchecked")
public void resolveReferences(final Entity entity) {
    final ManagedType<?> metaData = getClassMetamodel(entity);
    for (Attribute<?, ?> attribute : metaData.getAttributes()) {
        resolveReference(entity, attribute);
    }
}
项目:OpenCyclos    文件:JpaQueryHandler.java   
public void resolveReference(final Object entity, String propertyName) {
    final ManagedType<?> metaData = getClassMetamodel(entity);
    if (!metaData.getAttributes().contains(propertyName)) {
        throw new PropertyException(entity, propertyName);
    }
    Attribute<?, ?> attribute = metaData.getAttribute(propertyName);
    resolveReference(entity, attribute);
}
项目:OpenCyclos    文件:JpaQueryHandler.java   
private void resolveReference(final Object entity, Attribute<?, ?> attribute) {
     if (attribute.isCollection() && !Map.class.isAssignableFrom(attribute.getJavaType())) {
        // Properties that are collections of other entities
        final Collection<?> current = PropertyHelper.get(entity, attribute.getName());
        if (current != null) {
            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 = entityManager.find(EntityHelper.getRealClass(e), e.getId());
                }
                resolved.add(e);
            }
            if (isEntityCollection) {
                PropertyHelper.set(entity, attribute.getName(), resolved);
            }
        }
    } else if (attribute.isAssociation() && !Map.class.isAssignableFrom(attribute.getJavaType())) {
        // Properties that are relationships to other entities
        Entity rel = PropertyHelper.get(entity, attribute.getName());
        if (rel instanceof EntityReference) {
            rel = entityManager.find(EntityHelper.getRealClass(rel), rel.getId());
            PropertyHelper.set(entity, attribute.getName(), rel);
        }
    }
}