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

项目:redg    文件:JpaMetamodelRedGProvider.java   
private void analyzeAttributes(ManagedType<?> managedType, String targetTableName) {
    managedType.getSingularAttributes().forEach(attribute -> {
        ManagedType<?> targetEntity = managedTypesByClass.get(attribute.getJavaType());
        if (targetEntity != null && attribute.getType() instanceof EmbeddableType) {
            analyzeAttributes((EmbeddableType) attribute.getType(), targetTableName);
        } else if (targetEntity != null && attribute.getType() instanceof IdentifiableType) { // this is a relation
            Map<String, String> referenceColumnNamesMap =
                    getReferenceColumnNamesMapForReferenceAttribute(attribute, targetEntity);
            singularAttributesByForeignKeyRelation.put(
                    new ForeignKeyRelation(targetTableName, getTableName(targetEntity.getJavaType()), referenceColumnNamesMap),
                    attribute
            );
        } else {
            String columnName = getSingularAttributeColumnName(attribute);
            singularAttributesByColumnName.put(new QualifiedColumnName(targetTableName, columnName), attribute);
        }
    });
}
项目:redg    文件:JpaMetamodelRedGProvider.java   
private Map<String, String> getReferenceColumnNamesMapForReferenceAttribute(SingularAttribute<?, ?> attribute, ManagedType<?> targetEntity) {
    List<String> idAttributeNames = targetEntity.getSingularAttributes().stream()
               .filter(this::isIdAttribute)
               .map(this::getSingularAttributeColumnName)
               .collect(Collectors.toList());

    JoinColumns joinColumnsAnnotation =
               ((AnnotatedElement) attribute.getJavaMember()).getAnnotation(JoinColumns.class);
    JoinColumn joinColumnAnnotation =
               ((AnnotatedElement) attribute.getJavaMember()).getAnnotation(JoinColumn.class);
    JoinColumn[] joinColumns = joinColumnsAnnotation != null ? joinColumnsAnnotation.value() :
               joinColumnAnnotation != null ? new JoinColumn[]{joinColumnAnnotation} : null;
    Map<String, String> referenceColumnNamesMap;
    if (joinColumns != null) {
           referenceColumnNamesMap = Arrays.stream(joinColumns)
                   .collect(Collectors.toMap(JoinColumn::name, joinColumn ->
                           joinColumn.referencedColumnName().length() > 0 ? joinColumn.referencedColumnName() :
                                   idAttributeNames.get(0)));
       } else {
           referenceColumnNamesMap = idAttributeNames.stream()
                   .collect(Collectors.toMap(idAttributeName -> attribute.getName().toUpperCase() + "_"
                           + idAttributeName, idAttributeName -> idAttributeName));
       }
    return referenceColumnNamesMap;
}
项目: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()]);
}
项目:rpb    文件:ByExampleUtil.java   
/**
 * Add a predicate for each simple property whose value is not null.
 */
public <T> List<Predicate> byExample(ManagedType<T> mt, Path<T> mtPath, final T mtValue, SearchParameters sp, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE //
                || attr.getPersistentAttributeType() == ONE_TO_ONE //
                || attr.getPersistentAttributeType() == EMBEDDED) {
            continue;
        }

        Object attrValue = getValue(mtValue, attr);
        if (attrValue != null) {
            if (attr.getJavaType() == String.class) {
                if (isNotEmpty((String) attrValue)) {
                    predicates.add(JpaUtil.stringPredicate(mtPath.get(stringAttribute(mt, attr)), attrValue, sp, builder));
                }
            } else {
                predicates.add(builder.equal(mtPath.get(attribute(mt, attr)), attrValue));
            }
        }
    }
    return predicates;
}
项目:rpb    文件:ByExampleUtil.java   
/**
 * Invoke byExample method for each not null x-to-one association when their pk is not set. This allows you to search entities based on an associated
 * entity's properties value.
 */
@SuppressWarnings("unchecked")
public <T extends Identifiable<?>, M2O extends Identifiable<?>> List<Predicate> byExampleOnXToOne(ManagedType<T> mt, Root<T> mtPath, final T mtValue,
        SearchParameters sp, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) { //
            M2O m2oValue = (M2O) getValue(mtValue, mt.getAttribute(attr.getName()));
            if (m2oValue != null && !m2oValue.isIdSet()) {
                Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType();
                ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType);
                Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr);
                predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder));
            }
        }
    }
    return predicates;
}
项目:katharsis-framework    文件:JpaModule.java   
/**
 * Constructor used on server side.
 */
private JpaModule(EntityManagerFactory emFactory, EntityManager em, TransactionRunner transactionRunner) {
    this();

    this.emFactory = emFactory;
    this.em = em;
    this.transactionRunner = transactionRunner;
    setQueryFactory(JpaCriteriaQueryFactory.newInstance());

    if (emFactory != null) {
        Set<ManagedType<?>> managedTypes = emFactory.getMetamodel().getManagedTypes();
        for (ManagedType<?> managedType : managedTypes) {
            Class<?> managedJavaType = managedType.getJavaType();
            MetaElement meta = jpaMetaLookup.getMeta(managedJavaType, MetaJpaDataObject.class);
            if (meta instanceof MetaEntity) {
                addRepository(JpaRepositoryConfig.builder(managedJavaType).build());
            }
        }
    }
    this.setRepositoryFactory(new DefaultJpaRepositoryFactory());
}
项目: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;
}
项目:jpasecurity    文件:ManagedTypeFilter.java   
public ManagedType<?> filter(Class<?> type) {
    if (type == null) {
        throw new IllegalArgumentException("type not found");
    }
    try {
        return metamodel.managedType(type);
    } catch (IllegalArgumentException original) {
        // hibernate bug! Manged types don't contain embeddables
        try {
            return metamodel.embeddable(type);
        } catch (IllegalArgumentException e) {
            if (type.getSuperclass() == Object.class) {
                throw original;
            }
            try {
                return filter(type.getSuperclass()); // handles proxy classes
            } catch (IllegalArgumentException e2) {
                throw original;
            }
        }
    }
}
项目: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()));
        }
    }

}
项目:kc-rice    文件:JpaPersistenceProvider.java   
/**
 * {@inheritDoc}
 */
@Override
public boolean handles(final Class<?> type) {
    if (managedTypesCache == null) {
        managedTypesCache = new HashSet<Class<?>>();

        Set<ManagedType<?>> managedTypes = sharedEntityManager.getMetamodel().getManagedTypes();
        for (ManagedType managedType : managedTypes) {
            managedTypesCache.add(managedType.getJavaType());
        }
    }

    if (managedTypesCache.contains(type)) {
        return true;
    } else {
        return false;
    }
}
项目:rpb    文件:ByExampleUtil.java   
/**
 * Add a predicate for each simple property whose value is not null.
 */
public <T> List<Predicate> byExample(ManagedType<T> mt, Path<T> mtPath, final T mtValue, SearchParameters sp, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE //
                || attr.getPersistentAttributeType() == ONE_TO_ONE //
                || attr.getPersistentAttributeType() == EMBEDDED) {
            continue;
        }

        Object attrValue = getValue(mtValue, attr);
        if (attrValue != null) {
            if (attr.getJavaType() == String.class) {
                if (isNotEmpty((String) attrValue)) {
                    predicates.add(JpaUtil.stringPredicate(mtPath.get(stringAttribute(mt, attr)), attrValue, sp, builder));
                }
            } else {
                predicates.add(builder.equal(mtPath.get(attribute(mt, attr)), attrValue));
            }
        }
    }
    return predicates;
}
项目:rpb    文件:ByExampleUtil.java   
/**
 * Invoke byExample method for each not null x-to-one association when their pk is not set. This allows you to search entities based on an associated
 * entity's properties value.
 */
@SuppressWarnings("unchecked")
public <T extends Identifiable<?>, M2O extends Identifiable<?>> List<Predicate> byExampleOnXToOne(ManagedType<T> mt, Root<T> mtPath, final T mtValue,
        SearchParameters sp, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) { //
            M2O m2oValue = (M2O) getValue(mtValue, mt.getAttribute(attr.getName()));
            if (m2oValue != null && !m2oValue.isIdSet()) {
                Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType();
                ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType);
                Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr);
                predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder));
            }
        }
    }
    return predicates;
}
项目:javaee-lab    文件:ByExampleUtil.java   
public <T> List<Predicate> byExample(ManagedType<T> mt, Path<T> mtPath, T mtValue, SearchParameters sp, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE //
                || attr.getPersistentAttributeType() == ONE_TO_ONE //
                || attr.getPersistentAttributeType() == EMBEDDED) {
            continue;
        }

        Object attrValue = jpaUtil.getValue(mtValue, attr);
        if (attrValue != null) {
            if (attr.getJavaType() == String.class) {
                if (isNotEmpty((String) attrValue)) {
                    predicates.add(jpaUtil.stringPredicate(mtPath.get(jpaUtil.stringAttribute(mt, attr)), attrValue, sp, builder));
                }
            } else {
                predicates.add(builder.equal(mtPath.get(jpaUtil.attribute(mt, attr)), attrValue));
            }
        }
    }
    return predicates;
}
项目:javaee-lab    文件:ByExampleUtil.java   
@SuppressWarnings("unchecked")
public <T extends Identifiable<?>, M2O extends Identifiable<?>> List<Predicate> byExampleOnXToOne(ManagedType<T> mt, Root<T> mtPath, T mtValue,
                                                                                                  SearchParameters sp, CriteriaBuilder builder) {
    List<Predicate> predicates = newArrayList();
    for (SingularAttribute<? super T, ?> attr : mt.getSingularAttributes()) {
        if (attr.getPersistentAttributeType() == MANY_TO_ONE || attr.getPersistentAttributeType() == ONE_TO_ONE) {
            M2O m2oValue = (M2O) jpaUtil.getValue(mtValue, mt.getAttribute(attr.getName()));
            Class<M2O> m2oType = (Class<M2O>) attr.getBindableJavaType();
            Path<M2O> m2oPath = (Path<M2O>) mtPath.get(attr);
            ManagedType<M2O> m2oMt = em.getMetamodel().entity(m2oType);
            if (m2oValue != null) {
                if (m2oValue.isIdSet()) { // we have an id, let's restrict only on this field
                    predicates.add(builder.equal(m2oPath.get("id"), m2oValue.getId()));
                } else {
                    predicates.addAll(byExample(m2oMt, m2oPath, m2oValue, sp, builder));
                }
            }
        }
    }
    return predicates;
}
项目:midpoint    文件:EntityRegistry.java   
public boolean hasAttributePathOverride(ManagedType type, ItemPath pathOverride) {
    Map<ItemPath, Attribute> overrides = attributeNamePathOverrides.get(type);
    if (overrides == null) {
        return false;
    }

    ItemPath namedOnly = pathOverride.namedSegmentsOnly();

    for (ItemPath path : overrides.keySet()) {
        if (path.startsWith(namedOnly) || path.equals(namedOnly)) {
            return true;
        }
    }

    return false;
}
项目:spearal-jpa2    文件:SpearalConfigurator.java   
public static void init(SpearalFactory spearalFactory, EntityManagerFactory entityManagerFactory) {
    SpearalContext context = spearalFactory.getContext();

    Set<Class<?>> entityClasses = new HashSet<Class<?>>();
    for (ManagedType<?> managedType : entityManagerFactory.getMetamodel().getManagedTypes()) {
        List<String> unfilterablePropertiesList = new ArrayList<String>();
        for (SingularAttribute<?, ?> attribute : managedType.getSingularAttributes()) {
            if (attribute.isId() || attribute.isVersion())
                unfilterablePropertiesList.add(attribute.getName());
        }
        String[] unfilterableProperties = unfilterablePropertiesList.toArray(new String[unfilterablePropertiesList.size()]);

        Class<?> entityClass = managedType.getJavaType();
        context.configure(new SimpleUnfilterablePropertiesProvider(entityClass, unfilterableProperties));
        entityClasses.add(entityClass);
    }
    context.configure(new EntityDescriptorFactory(entityClasses));
}
项目:spearal-jpa2    文件:PartialEntityResolver.java   
public PartialEntityMap introspect(Object entity) {
    PartialEntityMap proxyMap = new PartialEntityMap();

    PartialObjectProxy partialObject = (entity instanceof PartialObjectProxy ? (PartialObjectProxy)entity : null);
    Class<?> entityClass = (partialObject != null ? entity.getClass().getSuperclass() : entity.getClass());
    ManagedType<?> managedType = getManagedType(entityClass);

    if (managedType == null || managedType.getPersistenceType() != PersistenceType.ENTITY)
        throw new PersistenceException("Not a managed entity: " + entityClass);

    if (partialObject != null)
        proxyMap.add(partialObject);

    introspect(entity, proxyMap, new IdentityHashMap<Object, Boolean>());

    return proxyMap;
}
项目:breeze.server.java    文件:JPAMetadata.java   
/**
     * Build the raw Breeze metadata.  This will then get wrapped with a strongly typed wrapper. The internal
     * rawMetadata can be converted to JSON and sent to the Breeze client.
     */
    @Override
    public RawMetadata buildRawMetadata() {
        initMap();

        Set<ManagedType<?>> classMeta = _emFactory.getMetamodel().getManagedTypes();

//        classMeta.clear(); // TODO test only
//        classMeta.add(_emFactory.getMetamodel().entity(northwind.jpamodel.Employee.class));

        for (ManagedType<?> meta : classMeta) {
            addClass(meta);
        }

        return _rawMetadata;
    }
项目:rice    文件:JpaPersistenceProvider.java   
/**
 * {@inheritDoc}
 */
@Override
public boolean handles(final Class<?> type) {
    if (managedTypesCache == null) {
        managedTypesCache = new HashSet<Class<?>>();

        Set<ManagedType<?>> managedTypes = sharedEntityManager.getMetamodel().getManagedTypes();
        for (ManagedType managedType : managedTypes) {
            managedTypesCache.add(managedType.getJavaType());
        }
    }

    if (managedTypesCache.contains(type)) {
        return true;
    } else {
        return false;
    }
}
项目:nemo-utils    文件:BaseJPADAO.java   
/**
 * Constructs a predicate using Java EE's Criteria API depending on the type of criterion.
 * 
 * @param cb
 *          The criteria builder.
 * @param path
 *          The path object (root, join, etc.).
 * @param model
 *          The model object (managed type, entity type, etc.).
 * @param criterion
 *          The criterion used to build the predicate.
 * 
 * @return The predicate object that can be used to compose a CriteriaQuery.
 * @see javax.persistence.criteria.CriteriaQuery
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Predicate createPredicate(CriteriaBuilder cb, From path, ManagedType model, Criterion criterion) {
    // Remove @SupressWarnings and add the correct generic types to all operations.

    // Obtains the final path. This is done in case navigation is required.
    Path finalPath = findPath(path, model, criterion.getFieldName());

    // Check the criterion type.
    switch (criterion.getType()) {
    case IS_NULL:
        return cb.isNull(finalPath);

    case IS_NOT_NULL:
        return cb.isNotNull(finalPath);

    case EQUALS:
        return cb.equal(finalPath, criterion.getParam());

    case LIKE:
        return cb.like(cb.lower(finalPath), "%" + criterion.getParam().toString().toLowerCase() + "%");
    }

    // Thrown an exception in the case of an unknown criterion type.
    throw new IllegalArgumentException("Unknown criterion type: " + this);
}
项目:midpoint    文件:EntityRegistry.java   
public boolean hasAttributePathOverride(ManagedType type, ItemPath pathOverride) {
    Map<ItemPath, Attribute> overrides = attributeNamePathOverrides.get(type);
    if (overrides == null) {
        return false;
    }

    ItemPath namedOnly = pathOverride.namedSegmentsOnly();

    for (ItemPath path : overrides.keySet()) {
        if (path.startsWith(namedOnly) || path.equals(namedOnly)) {
            return true;
        }
    }

    return false;
}
项目:screensaver    文件:TestDataFactory.java   
/**
 * Adds an entity builder for every entity type that does not already have a builder (in other words, a builder that
 * is added for a entity type before this method is called will be the entity type's default builder).
 */
private void addDefaultEntityBuilders()
{
  for (ManagedType<?> managedType : entityManagerFactory.getMetamodel().getManagedTypes()) {
    Class<?> managedClass = managedType.getJavaType();
    if (AbstractEntity.class.isAssignableFrom(managedClass)) {
      if (Modifier.isAbstract(managedClass.getModifiers())) {
        continue;
      }
      Class<? extends AbstractEntity> entityClass = (Class<? extends AbstractEntity>) managedClass;
      Class<? extends AbstractEntity> parentClass = ModelIntrospectionUtil.getParent(entityClass);
      if (!!!builders.containsKey(entityClass)) {
        if (parentClass != null) {
          addBuilder(new ParentedEntityBuilder(entityClass, genericEntityDao, this));
        }
        else {
          addBuilder(new EntityBuilder(entityClass, genericEntityDao, this));
        }
      }
    }
  }
}
项目:screensaver    文件:ModelTestCoverageTest.java   
public void testModelTestCoverage()
{
  assertNotNull(entityManagerFactory);
  for (ManagedType<?> managedType : entityManagerFactory.getMetamodel().getManagedTypes()) {
    Class<?> entityClass = managedType.getJavaType();
    String entityClassName = entityClass.getSimpleName();
    if (Modifier.isAbstract(entityClass.getModifiers())) {
      continue;
    }
    if (entityClass.getAnnotation(Embeddable.class) != null) {
      continue;
    }
    try {
      Class.forName(entityClass.getName() + "Test");
    }
    catch (ClassNotFoundException e) {
      fail("missing test class for " + entityClassName);
    }
  }
}
项目:screensaver    文件:IsVersionedTester.java   
/**
 * Test that the entity is versioned, that the name of the version property is "version",
 * and that the version property is not nullable.
 */
private void testIsVersioned()
{

  org.hibernate.annotations.Entity entityAnnotation =
    _entityClass.getAnnotation(org.hibernate.annotations.Entity.class);
  if (entityAnnotation != null && ! entityAnnotation.mutable()) {
    return;
  }
  if (_entityClass.getAnnotation(Immutable.class) != null) {
    return;
  }

  ManagedType<? extends AbstractEntity> type = _entityManagerFactory.getMetamodel().managedType(_entityClass);
  SingularAttribute id = ((IdentifiableType) type).getId(((IdentifiableType) type).getIdType().getJavaType());
  assertTrue("hibernate class is versioned: " + _entityClass, ((IdentifiableType) type).hasVersionAttribute());

  assertFalse("version property is not nullable: " + _entityClass, ((IdentifiableType) type).getVersion(Integer.class).isOptional());
}
项目:crnk-framework    文件:JpaModuleConfig.java   
/**
 * Exposes all entities as repositories.
 */
public void exposeAllEntities(EntityManagerFactory emf) {
    Set<ManagedType<?>> managedTypes = emf.getMetamodel().getManagedTypes();
    for (ManagedType<?> managedType : managedTypes) {
        Class<?> managedJavaType = managedType.getJavaType();
        if (managedJavaType.getAnnotation(Entity.class) != null) {
            addRepository(JpaRepositoryConfig.builder(managedJavaType).build());
        }
    }
}
项目:rpb    文件:ByExampleUtil.java   
public <T extends Identifiable<?>> Predicate byExampleOnEntity(Root<T> rootPath, final T entityValue, SearchParameters sp, CriteriaBuilder builder) {
    if (entityValue == null) {
        return null;
    }

    Class<T> type = rootPath.getModel().getBindableJavaType();
    ManagedType<T> mt = em.getMetamodel().entity(type);

    List<Predicate> predicates = newArrayList();
    predicates.addAll(byExample(mt, rootPath, entityValue, sp, builder));
    predicates.addAll(byExampleOnCompositePk(rootPath, entityValue, sp, builder));
    predicates.addAll(byExampleOnXToOne(mt, rootPath, entityValue, sp, builder)); // 1 level deep only
    predicates.addAll(byExampleOnManyToMany(mt, rootPath, entityValue, sp, builder));
    return JpaUtil.andPredicate(builder, predicates);
}
项目:rpb    文件:ByExampleUtil.java   
public <E> Predicate byExampleOnEmbeddable(Path<E> embeddablePath, final E embeddableValue, SearchParameters sp, CriteriaBuilder builder) {
    if (embeddableValue == null) {
        return null;
    }

    Class<E> type = embeddablePath.getModel().getBindableJavaType();
    ManagedType<E> mt = em.getMetamodel().embeddable(type); // note: calling .managedType() does not work

    return JpaUtil.andPredicate(builder, byExample(mt, embeddablePath, embeddableValue, sp, builder));
}
项目:jpasecurity    文件:AccessRulesParser.java   
private ListMap<Class<?>, Permit> parsePermissions() {
    ListMap<Class<?>, Permit> permissions = new ListHashMap<Class<?>, Permit>();
    for (ManagedType<?> managedType: metamodel.getManagedTypes()) {
        Class<?> type = managedType.getJavaType();
        Permit permit = type.getAnnotation(Permit.class);
        if (permit != null) {
            permissions.add(type, permit);
        }
        PermitAny permitAny = type.getAnnotation(PermitAny.class);
        if (permitAny != null) {
            permissions.addAll(type, Arrays.asList(permitAny.value()));
        }
    }
    return permissions;
}
项目: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    文件:ManagedTypeFilter.java   
public Collection<ManagedType<?>> filterAll(Class<?> type) {
    Set<ManagedType<?>> filteredTypes = new HashSet<ManagedType<?>>();
    for (ManagedType<?> managedType: metamodel.getManagedTypes()) {
        if (type.isAssignableFrom(managedType.getJavaType())) {
            filteredTypes.add(managedType);
        }
    }
    return filteredTypes;
}
项目:jpasecurity    文件:ManagedTypeFilter.java   
public Collection<EntityType<?>> filterEntities(Class<?> type) {
    Set<EntityType<?>> filteredTypes = new HashSet<EntityType<?>>();
    for (ManagedType<?> managedType: metamodel.getManagedTypes()) {
        if (type.isAssignableFrom(managedType.getJavaType()) && (managedType instanceof EntityType)) {
            filteredTypes.add((EntityType<?>)managedType);
        }
    }
    return filteredTypes;
}
项目:jpasecurity    文件:NamedQueryParser.java   
public ConcurrentMap<String, String> parseNamedQueries() {
    ConcurrentMap<String, String> namedQueries = new ConcurrentHashMap<String, String>();
    for (ManagedType<?> managedType: metamodel.getManagedTypes()) {
        namedQueries.putAll(parseNamedQueries(managedType.getJavaType()));
    }
    namedQueries.putAll(parseNamedQueries(ormXmlLocations));
    return namedQueries;
}
项目:ibankapp-base    文件:ByIdsSpecification.java   
/**
 * 获取按ID集合进行实体查询的Predicate.
 *
 * @param root 实体类ROOT
 * @param query 条件查询
 * @param cb 查询构建器
 */
@Override
@SuppressWarnings("unchecked")
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

  ManagedType type = em.getMetamodel().managedType(entityClass);

  IdentifiableType identifiableType = (IdentifiableType) type;

  Path<?> path = root.get(identifiableType.getId(identifiableType.getIdType().getJavaType()));

  parameter = cb.parameter(Iterable.class);
  return path.in(parameter);
}
项目:springJpaKata    文件:PersonMetaModelTest.java   
@Test
public void shouldMetaModelWork() {
    Metamodel mm = emf.getMetamodel();
    Set<ManagedType<?>> managedTypes = mm.getManagedTypes();
    for(ManagedType<?> mType: managedTypes){
        log.info("{},{}",mType.getJavaType(),mType.getPersistenceType());
    }

}
项目: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);
    }
}