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); } }); }
/** * {@inheritDoc} */ @Override protected synchronized void initializeMetadata(Collection<Class<?>> types) { LOG.info("Initializing JPA Metadata from " + entityManager); masterMetadataMap.clear(); // QUESTION: When is JPA loaded so this service can initialize itself? // Build and store the map for ( IdentifiableType<?> identifiableType : entityManager.getMetamodel().getEntities() ) { //Only extract the metadata if EntityType and not a MappedSuperClass if(identifiableType instanceof EntityType<?>){ EntityType<?> type = (EntityType<?>)identifiableType; try { masterMetadataMap.put(type.getBindableJavaType(), getMetadataForClass(type.getBindableJavaType())); if (LOG.isDebugEnabled()) { LOG.debug("Added Metadata For: " + type.getBindableJavaType()); } } catch (Exception ex) { LOG.error("Error obtaining JPA metadata for type: " + type.getJavaType(), ex); } } } }
/** * 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()); }
/** * Return the ORM path from the given rule. * * @param root * root * @param path * path * @param <U> * The entity type referenced by the {@link Root} */ @SuppressWarnings("unchecked") protected <U, T> Path<T> getOrmPath(final Root<U> root, final String path) { PathImplementor<?> currentPath = (PathImplementor<?>) root; for (final String pathFragment : path.split(DELIMITERS)) { currentPath = getNextPath(pathFragment, (From<?, ?>) currentPath); } // Fail safe identifier access for non singular target path if (currentPath instanceof SingularAttributeJoin) { currentPath = getNextPath(((IdentifiableType<?>) currentPath.getModel()).getId(Object.class).getName(), (From<?, ?>) currentPath); } return (Path<T>) currentPath; }
/** * 获取按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); }
/** * 构造函数. * * @param source id类型 */ @SuppressWarnings("unchecked") IdMetadata(IdentifiableType<T> source) { this.attributes = (Set<SingularAttribute<? super T, ?>>) (source.hasSingleIdAttribute() ? Collections.singleton(source.getId(source.getIdType().getJavaType())) : source.getIdClassAttributes()); }
/** Get the id attribute for an entity, or null if it doesn't have one */ SingularAttribute<?,?> getSingleIdAttribute(IdentifiableType<?> type) { if (type.hasSingleIdAttribute()) { // This throws when id is a primitive //SingularAttribute<?,?> idAttr = idmeta.getId(idType.getJavaType()); for (SingularAttribute<?,?> testAttr : type.getDeclaredSingularAttributes()) { if (testAttr.isId()) { return testAttr; } } } return null; }
/** Get the column names for the ID attribute of the given type */ List<String> getIdAttributeColumnNames(IdentifiableType<?> type) { Attribute idattr = getSingleIdAttribute(type); if (idattr != null) { return getAttributeColumnNames(idattr); } else { List<String> names = new ArrayList<String>(); for (Attribute id: type.getIdClassAttributes()) { names.addAll(getAttributeColumnNames(id)); } return names; } }
/** * Test that the identifier getter method is public, the identifier getter method is private, * both are instance, and the arg/return types match. */ private void testIdentifierAccessorModifiers() { if (ModelIntrospectionUtil.isEntitySubclass(_entityClass)) { // entity subclasses depend on their superclass for identifier methods, // which will be tested when that superclass is tested return; } String identifierPropertyName; ManagedType<? extends AbstractEntity> type = _entityManagerFactory.getMetamodel().managedType(_entityClass); Class idType = ((IdentifiableType) type).getIdType().getJavaType(); SingularAttribute id = ((IdentifiableType) type).getId(idType); identifierPropertyName = id.getName(); Method identifierGetter = ModelIntrospectionUtil.getGetterMethodForPropertyName(_entityClass, identifierPropertyName); assertTrue("public entity ID getter for " + _entityClass, Modifier.isPublic(identifierGetter.getModifiers())); assertFalse("instance entity ID getter for " + _entityClass, Modifier.isStatic(identifierGetter.getModifiers())); Type identifierType = identifierGetter.getGenericReturnType(); assertNotNull("identifier getter returns type", identifierType); Method identifierSetter = ModelIntrospectionUtil.getSetterMethodForPropertyName(_entityClass, identifierPropertyName, (Class) identifierType); assertTrue("private entity ID setter for " + _entityClass, Modifier.isPrivate(identifierSetter.getModifiers())); assertFalse("instance entity ID setter for " + _entityClass, Modifier.isStatic(identifierSetter.getModifiers())); }
private void testIdentifierMetadata() { if (ModelIntrospectionUtil.isEntitySubclass(_entityClass)) { // entity subclasses depend on their superclass for identifier methods // TODO: run this test on the superclasses return; } ManagedType<? extends AbstractEntity> type = _entityManagerFactory.getMetamodel().managedType(_entityClass); assertTrue("hibernate class has an identifier: " + _entityClass, ((IdentifiableType) type).hasSingleIdAttribute()); Class idType = ((IdentifiableType) type).getIdType().getJavaType(); String idName = ((IdentifiableType) type).getId(idType).getName(); testGeneratedValueAppropriateness(_entityClass.toString(), idName); }
public Class<?> getIdType(ManagedType<?> managedType) { return ((IdentifiableType<?>) managedType).getIdType().getJavaType(); }
@Override public IdentifiableType<? super X> getSupertype() { return null; }
private Object resolve(PartialObjectProxy partialObject, List<Reference> references, Map<PartialObjectProxy, Object> resolved) { Class<?> entityClass = partialObject.getClass().getSuperclass(); Object entity = newInstance(entityClass); for (Property property : partialObject.$getDefinedProperties()) setPropertyValue(entity, property, getPropertyValue(partialObject, property)); if (partialObject.$hasUndefinedProperties()) { ManagedType<?> managedType = getManagedType(entityClass); switch (managedType.getPersistenceType()) { case BASIC: case MAPPED_SUPERCLASS: throw new UnsupportedOperationException("Internal error: " + entityClass.getName() + " - " + managedType.getPersistenceType()); case ENTITY: { Object id = getId(partialObject, (IdentifiableType<?>)managedType); if (id != null) { Object loaded = entityManager.find(managedType.getJavaType(), id); if (loaded != null) { for (Attribute<?, ?> attribute : managedType.getAttributes()) { if (!partialObject.$isDefined(attribute.getName())) { Accessor accessor = getAttributeAccessor(attribute); accessor.setter.setValue(entity, accessor.getter.getValue(loaded)); } } } } break; } case EMBEDDABLE: { throw new UnsupportedOperationException("Partial Embeddable: " + entityClass.getName()); } } } for (Reference reference : references) reference.set(resolved, entity); resolved.put(partialObject, entity); return entity; }
/** * Add the metadata for an entity or mapped superclass. * Embeddables are skipped, and only added when they are the property of an entity. * * @param meta */ void addClass(ManagedType<?> meta) { if (!(meta instanceof IdentifiableType)) return; // skip embeddable types until they are encountered via an entity Class type = meta.getJavaType(); String classKey = getEntityTypeName(type); HashMap<String, Object> cmap = new LinkedHashMap<String, Object>(); _typeList.add(cmap); cmap.put("shortName", type.getSimpleName()); cmap.put("namespace", type.getPackage().getName()); IdentifiableType<?> idmeta = (IdentifiableType) meta; IdentifiableType superMeta = idmeta.getSupertype(); if (superMeta != null) { Class superClass = superMeta.getJavaType(); cmap.put("baseTypeName", getEntityTypeName(superClass)); } String genType = "None"; if (idmeta.hasSingleIdAttribute()) { SingularAttribute<?,?> idAttr = getSingleIdAttribute(idmeta); Member member = idAttr.getJavaMember(); GeneratedValue genValueAnn = ((AnnotatedElement)member).getAnnotation(GeneratedValue.class); if (genValueAnn != null) { // String generator = genValueAnn.generator(); GenerationType strategy = genValueAnn.strategy(); if (strategy == GenerationType.SEQUENCE || strategy == GenerationType.TABLE) genType = "KeyGenerator"; else if (strategy == GenerationType.IDENTITY || strategy == GenerationType.AUTO) genType = "Identity"; // not sure what to do about AUTO cmap.put("autoGeneratedKeyType", genType); } } String resourceName = pluralize(type.getSimpleName()); // TODO find the real name cmap.put("defaultResourceName", resourceName); _resourceMap.put(resourceName, classKey); ArrayList<HashMap<String, Object>> dataArrayList = new ArrayList<HashMap<String, Object>>(); cmap.put("dataProperties", dataArrayList); ArrayList<HashMap<String, Object>> navArrayList = new ArrayList<HashMap<String, Object>>(); cmap.put("navigationProperties", navArrayList); addClassProperties(meta, dataArrayList, navArrayList); }
/** * 构造函数. * * @param domainClass 实体类CLASS * @param metamodel 模型元数据,可从jpa的实体管理器EntityManage获取 */ public EntityInformation(Class<T> domainClass, Metamodel metamodel) { ManagedType<T> type = metamodel.managedType(domainClass); this.entityName = ((EntityType<?>) type).getName(); IdentifiableType<T> identifiableType = (IdentifiableType<T>) type; this.idMetadata = new IdMetadata<T>(identifiableType); }