javax.persistence.metamodel.ManagedType Java Examples

The following examples show how to use javax.persistence.metamodel.ManagedType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JpaPersistenceProvider.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * {@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;
    }
}
 
Example #2
Source File: RSQLVisitorBase.java    From rsql-jpa-specification with MIT License 6 votes vote down vote up
@SneakyThrows(Exception.class)
protected <T> ManagedType<T> getManagedType(Class<T> cls) {
	Exception ex = null;
	if (getEntityManagerMap().size() > 0) {
		ManagedType<T> managedType = getManagedTypeMap().get(cls);
		if (managedType != null) {
			log.debug("Found managed type [{}] in cache", cls);
			return managedType;
		}
		for (Entry<String, EntityManager> entityManagerEntry : getEntityManagerMap().entrySet()) {
			try {
				managedType = entityManagerEntry.getValue().getMetamodel().managedType(cls);
				getManagedTypeMap().put(cls, managedType);
				log.info("Found managed type [{}] in EntityManager [{}]", cls, entityManagerEntry.getKey());
				return managedType;
			} catch (Exception e) {
				if (e != null) {
					ex = e;
				}
				log.debug("[{}] not found in EntityManager [{}] due to [{}]", cls, entityManagerEntry.getKey(), e == null ? "-" : e.getMessage());
			}
		}
	}
	log.error("[{}] not found in EntityManager{}: [{}]", cls, getEntityManagerMap().size() > 1 ? "s" : "", StringUtils.collectionToCommaDelimitedString(getEntityManagerMap().keySet()));
	throw ex != null ? ex : new IllegalStateException("No entity manager bean found in application context");
}
 
Example #3
Source File: RSQLVisitorBase.java    From rsql-jpa-specification with MIT License 6 votes vote down vote up
protected <T> ManagedType<T> getManagedElementCollectionType(String mappedProperty, ManagedType<T> classMetadata) {
	try {
		Class<?> cls = findPropertyType(mappedProperty, classMetadata);
		if (!cls.isPrimitive() && !primitiveToWrapper.containsValue(cls) && !cls.equals(String.class) && getEntityManagerMap().size() > 0) {
			ManagedType<T> managedType = getManagedTypeMap().get(cls);
			if (managedType != null) {
				log.debug("Found managed type [{}] in cache", cls);
				return managedType;
			}
			for (Entry<String, EntityManager> entityManagerEntry : getEntityManagerMap().entrySet()) {
				managedType = (ManagedType<T>) entityManagerEntry.getValue().getMetamodel().managedType(cls);
				getManagedTypeMap().put(cls, managedType);
				log.info("Found managed type [{}] in EntityManager [{}]", cls, entityManagerEntry.getKey());
				return managedType;
			}
		}
	} catch (Exception e) {
		log.warn("Unable to get the managed type of [{}]", mappedProperty, e);
	}
	return classMetadata;
}
 
Example #4
Source File: ByExampleUtil.java    From javaee-lab with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #5
Source File: ByExampleUtil.java    From javaee-lab with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: JpaModule.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #7
Source File: SubgraphImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("WeakerAccess")
public SubgraphImpl(
		SessionFactoryImplementor entityManagerFactory,
		ManagedType managedType,
		Class<T> subclass) {
	super( entityManagerFactory, true );
	this.managedType = managedType;
	this.subclass = subclass;
}
 
Example #8
Source File: RSQLVisitorBase.java    From rsql-jpa-specification with MIT License 5 votes vote down vote up
protected <T> boolean hasPropertyName(String property, ManagedType<T> classMetadata) {
	Set<Attribute<? super T, ?>> names = classMetadata.getAttributes();
	for (Attribute<? super T, ?> name : names) {
		if (name.getName().equals(property))
			return true;
	}
	return false;
}
 
Example #9
Source File: SingularAttributePath.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private ManagedType<X> resolveManagedType(SingularAttribute<?, X> attribute) {
	if ( Attribute.PersistentAttributeType.BASIC == attribute.getPersistentAttributeType() ) {
		return null;
	}
	else if ( Attribute.PersistentAttributeType.EMBEDDED == attribute.getPersistentAttributeType() ) {
		return (EmbeddableType<X>) attribute.getType();
	}
	else {
		return (IdentifiableType<X>) attribute.getType();
	}
}
 
Example #10
Source File: SingularAttributeJoin.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected ManagedType<? super X> locateManagedType() {
	if ( getModel().getBindableType() == Bindable.BindableType.ENTITY_TYPE ) {
		return (ManagedType<? super X>) getModel();
	}
	else if ( getModel().getBindableType() == Bindable.BindableType.SINGULAR_ATTRIBUTE ) {
		final Type joinedAttributeType = ( (SingularAttribute) getAttribute() ).getType();
		if ( !ManagedType.class.isInstance( joinedAttributeType ) ) {
			throw new UnsupportedOperationException(
					"Cannot further dereference attribute join [" + getPathIdentifier() + "] as its type is not a ManagedType"
			);
		}
		return (ManagedType<? super X>) joinedAttributeType;
	}
	else if ( getModel().getBindableType() == Bindable.BindableType.PLURAL_ATTRIBUTE ) {
		final Type elementType = ( (PluralAttribute) getAttribute() ).getElementType();
		if ( !ManagedType.class.isInstance( elementType ) ) {
			throw new UnsupportedOperationException(
					"Cannot further dereference attribute join [" + getPathIdentifier() + "] (plural) as its element type is not a ManagedType"
			);
		}
		return (ManagedType<? super X>) elementType;
	}

	return super.locateManagedType();
}
 
Example #11
Source File: MetamodelImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Set<ManagedType<?>> getManagedTypes() {
	final int setSize = CollectionHelper.determineProperSizing(
			jpaEntityTypeMap.size() + jpaMappedSuperclassTypeMap.size() + jpaEmbeddableTypes.size()
	);
	final Set<ManagedType<?>> managedTypes = new HashSet<ManagedType<?>>( setSize );
	managedTypes.addAll( jpaEntityTypesByEntityName.values() );
	managedTypes.addAll( jpaMappedSuperclassTypeMap.values() );
	managedTypes.addAll( jpaEmbeddableTypes );
	return managedTypes;
}
 
Example #12
Source File: MetamodelImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings({"unchecked"})
public <X> ManagedType<X> managedType(Class<X> cls) {
	ManagedType<?> type = jpaEntityTypeMap.get( cls );
	if ( type == null ) {
		type = jpaMappedSuperclassTypeMap.get( cls );
	}
	if ( type == null ) {
		type = jpaEmbeddableTypeMap.get( cls );
	}
	if ( type == null ) {
		throw new IllegalArgumentException( "Not a managed type: " + cls );
	}
	return (ManagedType<X>) type;
}
 
Example #13
Source File: Helper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static AttributeSource resolveAttributeSource(SessionFactoryImplementor sessionFactory, ManagedType managedType) {
	if ( EmbeddableTypeImpl.class.isInstance( managedType ) ) {
		return new ComponentAttributeSource( ( (EmbeddableTypeImpl) managedType ).getHibernateType() );
	}
	else if ( IdentifiableType.class.isInstance( managedType ) ) {
		final String entityName = managedType.getJavaType().getName();
		log.debugf( "Attempting to resolve managed type as entity using %s", entityName );
		return new EntityPersisterAttributeSource( sessionFactory.getEntityPersister( entityName ) );
	}
	else {
		throw new IllegalArgumentException(
				String.format( "Unknown ManagedType implementation [%s]", managedType.getClass() )
		);
	}
}
 
Example #14
Source File: JpaModuleConfig.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
        }
    }
}
 
Example #15
Source File: AttributeNodeImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("WeakerAccess")
public <X> AttributeNodeImpl(
		SessionFactoryImplementor sessionFactory,
		ManagedType managedType,
		Attribute<X, T> attribute) {
	this.sessionFactory = sessionFactory;
	this.managedType = managedType;
	this.attribute = attribute;
}
 
Example #16
Source File: AttributeNodeImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Intended only for use from {@link #makeImmutableCopy()}
 */
private AttributeNodeImpl(
		SessionFactoryImplementor sessionFactory,
		ManagedType managedType,
		Attribute<?, T> attribute,
		Map<Class, Subgraph> subgraphMap,
		Map<Class, Subgraph> keySubgraphMap) {
	this.sessionFactory = sessionFactory;
	this.managedType = managedType;
	this.attribute = attribute;
	this.subgraphMap = subgraphMap;
	this.keySubgraphMap = keySubgraphMap;
}
 
Example #17
Source File: RSQLVisitorBase.java    From rsql-jpa-specification with MIT License 5 votes vote down vote up
protected <T> Class<?> findPropertyType(String property, ManagedType<T> classMetadata) {
	Class<?> propertyType = null;
	if (classMetadata.getAttribute(property).isCollection()) {
		propertyType = ((PluralAttribute) classMetadata.getAttribute(property)).getBindableJavaType();
	} else {
		propertyType = classMetadata.getAttribute(property).getJavaType();
	}
	return propertyType;
}
 
Example #18
Source File: JpaSpecificationExecutorWithProjectionImpl.java    From specification-with-projection with MIT License 5 votes vote down vote up
static <T> Expression<T> toExpressionRecursively(From<?, ?> from, PropertyPath property, boolean isForSelection) {

        Bindable<?> propertyPathModel;
        Bindable<?> model = from.getModel();
        String segment = property.getSegment();

        if (model instanceof ManagedType) {

            /*
             *  Required to keep support for EclipseLink 2.4.x. TODO: Remove once we drop that (probably Dijkstra M1)
             *  See: https://bugs.eclipse.org/bugs/show_bug.cgi?id=413892
             */
            propertyPathModel = (Bindable<?>) ((ManagedType<?>) model).getAttribute(segment);
        } else {
            propertyPathModel = from.get(segment).getModel();
        }

        if (requiresJoin(propertyPathModel, model instanceof PluralAttribute, !property.hasNext(), isForSelection)
                && !isAlreadyFetched(from, segment)) {
            Join<?, ?> join = getOrCreateJoin(from, segment);
            return (Expression<T>) (property.hasNext() ? toExpressionRecursively(join, property.next(), isForSelection)
                    : join);
        } else {
            Path<Object> path = from.get(segment);
            return (Expression<T>) (property.hasNext() ? toExpressionRecursively(path, property.next()) : path);
        }
    }
 
Example #19
Source File: CustomRepositoryRestConfigurerAdapter.java    From spring-boot-jpa-data-rest-soft-delete with MIT License 5 votes vote down vote up
private List<Class<?>> getAllManagedEntityTypes(EntityManagerFactory entityManagerFactory) {
	List<Class<?>> entityClasses = new ArrayList<>();
	Metamodel metamodel = entityManagerFactory.getMetamodel();

	for (ManagedType<?> managedType : metamodel.getManagedTypes())
		if (managedType.getJavaType().isAnnotationPresent(Entity.class))
			entityClasses.add(managedType.getJavaType());

	return entityClasses;
}
 
Example #20
Source File: JpaUtil.java    From javaee-lab with Apache License 2.0 5 votes vote down vote up
public <T> boolean isPk(ManagedType<T> mt, SingularAttribute<? super T, ?> attr) {
    try {
        Method m = MethodUtils.getAccessibleMethod(mt.getJavaType(), "get" + WordUtils.capitalize(attr.getName()), (Class<?>) null);
        if (m != null && m.getAnnotation(Id.class) != null) {
            return true;
        }

        Field field = mt.getJavaType().getField(attr.getName());
        return field.getAnnotation(Id.class) != null;
    } catch (Exception e) {
        return false;
    }
}
 
Example #21
Source File: ByFullTextUtil.java    From javaee-lab with Apache License 2.0 5 votes vote down vote up
public <T extends Identifiable<?>> Predicate byExampleOnEntity(Root<T> rootPath, 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));
    return jpaUtil.orPredicate(builder, predicates);
}
 
Example #22
Source File: ByFullTextUtil.java    From javaee-lab with Apache License 2.0 5 votes vote down vote up
public <E> Predicate byExampleOnEmbeddable(Path<E> embeddablePath, 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.orPredicate(builder, byExample(mt, embeddablePath, embeddableValue, sp, builder));
}
 
Example #23
Source File: ByFullTextUtil.java    From javaee-lab with Apache License 2.0 5 votes vote down vote up
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 (!isPrimaryKey(mt, attr)) {
            continue;
        }

        Object attrValue = jpaUtil.getValue(mtValue, attr);
        if (attrValue != null) {
            predicates.add(builder.equal(mtPath.get(jpaUtil.attribute(mt, attr)), attrValue));
        }
    }
    return predicates;
}
 
Example #24
Source File: ByExampleUtil.java    From javaee-lab with Apache License 2.0 5 votes vote down vote up
public <T extends Identifiable<?>> Predicate byExampleOnEntity(Root<T> rootPath, T entityValue, CriteriaBuilder builder, SearchParameters sp) {
    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(byExampleOnXToMany(mt, rootPath, entityValue, sp, builder));
    return jpaUtil.concatPredicate(sp, builder, predicates);
}
 
Example #25
Source File: ByExampleUtil.java    From javaee-lab with Apache License 2.0 5 votes vote down vote up
public <E> Predicate byExampleOnEmbeddable(Path<E> embeddablePath, 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));
}
 
Example #26
Source File: JPAEdmReferentialConstraintTest.java    From olingo-odata2 with Apache License 2.0 4 votes vote down vote up
private ManagedType<?> getManagedTypeLocal() {
  ManagedTypeMock<String> managedTypeMock = new ManagedTypeMock<String>();
  return managedTypeMock;
}
 
Example #27
Source File: RSQLVisitorBase.java    From rsql-jpa-specification with MIT License 4 votes vote down vote up
protected <T> boolean isElementCollectionType(String property, ManagedType<T> classMetadata) {
	return classMetadata.getAttribute(property).getPersistentAttributeType() == PersistentAttributeType.ELEMENT_COLLECTION;
}
 
Example #28
Source File: JPAAttributeMock.java    From olingo-odata2 with Apache License 2.0 4 votes vote down vote up
@Override
public ManagedType<X> getDeclaringType() {
  return null;
}
 
Example #29
Source File: JPAMetaModelMock.java    From olingo-odata2 with Apache License 2.0 4 votes vote down vote up
@Override
public Set<ManagedType<?>> getManagedTypes() {
  return null;
}
 
Example #30
Source File: JPAEdmReferentialConstraintRoleTest.java    From olingo-odata2 with Apache License 2.0 4 votes vote down vote up
private ManagedType<?> getManagedTypeLocal() {
  ManagedTypeMock<String> managedTypeMock = new ManagedTypeMock<String>();
  return managedTypeMock;
}