下面列出了怎么用javax.persistence.metamodel.ManagedType的API类实例代码及写法,或者点击链接到github查看源代码。
@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");
}
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;
}
/**
* 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());
}
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;
}
@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;
}
/**
* {@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;
}
}
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;
}
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;
}
/**
* 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());
}
}
}
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() )
);
}
}
@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;
}
@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;
}
@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();
}
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();
}
}
@SuppressWarnings("WeakerAccess")
public <X> AttributeNodeImpl(
SessionFactoryImplementor sessionFactory,
ManagedType managedType,
Attribute<X, T> attribute) {
this.sessionFactory = sessionFactory;
this.managedType = managedType;
this.attribute = attribute;
}
/**
* 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;
}
@SuppressWarnings("WeakerAccess")
public SubgraphImpl(
SessionFactoryImplementor entityManagerFactory,
ManagedType managedType,
Class<T> subclass) {
super( entityManagerFactory, true );
this.managedType = managedType;
this.subclass = subclass;
}
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);
}
}
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;
}
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;
}
}
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);
}
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));
}
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;
}
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);
}
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));
}
protected Map<Class, ManagedType> getManagedTypeMap() {
return managedTypeMap != null ? managedTypeMap : Collections.emptyMap();
}
protected <T> boolean isEmbeddedType(String property, ManagedType<T> classMetadata) {
return classMetadata.getAttribute(property).getPersistentAttributeType() == PersistentAttributeType.EMBEDDED;
}
protected <T> boolean isElementCollectionType(String property, ManagedType<T> classMetadata) {
return classMetadata.getAttribute(property).getPersistentAttributeType() == PersistentAttributeType.ELEMENT_COLLECTION;
}
protected <T> boolean isAssociationType(String property, ManagedType<T> classMetadata) {
return classMetadata.getAttribute(property).isAssociation();
}
@Override
public ManagedType<X> getDeclaringType() {
return declaringType;
}