public static GroovyAwareJavassistProxyFactory buildProxyFactory( PersistentClass persistentClass) { GroovyAwareJavassistProxyFactory proxyFactory = new GroovyAwareJavassistProxyFactory(); @SuppressWarnings("unchecked") Set<Class<HibernateProxy>> proxyInterfaces = new HashSet<Class<HibernateProxy>>(); proxyInterfaces.add(HibernateProxy.class); final Class<?> javaClass = persistentClass.getMappedClass(); final Property identifierProperty = persistentClass.getIdentifierProperty(); final Method idGetterMethod = identifierProperty != null ? identifierProperty.getGetter(javaClass).getMethod() : null; final Method idSetterMethod = identifierProperty != null ? identifierProperty.getSetter(javaClass).getMethod() : null; final Type identifierType = persistentClass.hasEmbeddedIdentifier() ? persistentClass.getIdentifier().getType() : null; try { proxyFactory.postInstantiate( persistentClass.getEntityName(), javaClass, proxyInterfaces, idGetterMethod, idSetterMethod, identifierType instanceof CompositeType ? (CompositeType) identifierType : null); } catch (HibernateException e) { LOG.warn("Cannot instantiate proxy factory: " + e.getMessage()); return null; } return proxyFactory; }
private static Constructor getConstructor(PersistentClass persistentClass) { if (persistentClass == null || !persistentClass.hasPojoRepresentation()) { return null; } try { return ReflectHelper.getDefaultConstructor(persistentClass.getMappedClass()); } catch (Throwable t) { return null; } }
private void collectTypes() throws IOException, XMLStreamException, ClassNotFoundException, SecurityException, NoSuchMethodException { // super classes Iterator<?> superClassMappings = configuration.getMappedSuperclassMappings(); while (superClassMappings.hasNext()) { MappedSuperclass msc = (MappedSuperclass) superClassMappings.next(); EntityType entityType = createSuperType(msc.getMappedClass()); if (msc.getDeclaredIdentifierProperty() != null) { handleProperty(entityType, msc.getMappedClass(), msc.getDeclaredIdentifierProperty()); } Iterator<?> properties = msc.getDeclaredPropertyIterator(); while (properties.hasNext()) { handleProperty( entityType, msc.getMappedClass(), (org.hibernate.mapping.Property) properties.next()); } } // entity classes Iterator<?> classMappings = configuration.getClassMappings(); while (classMappings.hasNext()) { PersistentClass pc = (PersistentClass) classMappings.next(); EntityType entityType = createEntityType(pc.getMappedClass()); if (pc.getDeclaredIdentifierProperty() != null) { handleProperty(entityType, pc.getMappedClass(), pc.getDeclaredIdentifierProperty()); } else if (!pc.isInherited() && pc.hasIdentifierProperty()) { logger.info(entityType.toString() + pc.getIdentifierProperty()); handleProperty(entityType, pc.getMappedClass(), pc.getIdentifierProperty()); } Iterator<?> properties = pc.getDeclaredPropertyIterator(); while (properties.hasNext()) { handleProperty( entityType, pc.getMappedClass(), (org.hibernate.mapping.Property) properties.next()); } } }
@Override public boolean hasNext() { // we need to read the next non null one. getMappedClass() can return null and should be // ignored if (future != null) { return true; } do { if (!hibernatePersistentClassIterator.hasNext()) { future = null; return false; } final PersistentClass pc = hibernatePersistentClassIterator.next(); future = pc.getMappedClass(); } while (future == null); return true; }
/** initialize the validators, any non significant validators are not kept */ @SuppressWarnings("unchecked") public synchronized void initialize(final Configuration cfg) { if (!isInitialized) { Iterator<PersistentClass> classes = (Iterator<PersistentClass>) cfg.getClassMappings(); while (classes.hasNext()) { PersistentClass clazz = classes.next(); final Class mappedClass = clazz.getMappedClass(); ClassValidator validator = new ClassValidator(mappedClass); ValidatableElement element = new ValidatableElement(mappedClass, validator); addSubElement(clazz.getIdentifierProperty(), element); Iterator properties = clazz.getPropertyIterator(); while (properties.hasNext()) { addSubElement((Property) properties.next(), element); } if (element.subElements.size() != 0 || element.validator.hasValidationRules()) { validators.put(mappedClass, element); } } isInitialized = true; } }
public EntityMetamodel( PersistentClass persistentClass, AbstractEntityPersister persister, SessionFactoryImplementor sessionFactory) { this.sessionFactory = sessionFactory; this.persister = persister; name = persistentClass.getEntityName(); rootName = persistentClass.getRootClass().getEntityName(); entityType = sessionFactory.getTypeResolver().getTypeFactory().manyToOne(name); identifierAttribute = PropertyFactory.buildIdentifierAttribute( persistentClass, sessionFactory.getIdentifierGenerator(rootName)); versioned = persistentClass.isVersioned(); instrumentationMetadata = persistentClass.hasPojoRepresentation() ? Environment.getBytecodeProvider() .getEntityInstrumentationMetadata(persistentClass.getMappedClass()) : new NonPojoInstrumentationMetadata(persistentClass.getEntityName()); boolean hasLazy = false; propertySpan = persistentClass.getPropertyClosureSpan(); properties = new NonIdentifierAttribute[propertySpan]; List<Integer> naturalIdNumbers = new ArrayList<Integer>(); // temporary ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ propertyNames = new String[propertySpan]; propertyTypes = new Type[propertySpan]; propertyUpdateability = new boolean[propertySpan]; propertyInsertability = new boolean[propertySpan]; nonlazyPropertyUpdateability = new boolean[propertySpan]; propertyCheckability = new boolean[propertySpan]; propertyNullability = new boolean[propertySpan]; propertyVersionability = new boolean[propertySpan]; propertyLaziness = new boolean[propertySpan]; cascadeStyles = new CascadeStyle[propertySpan]; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // generated value strategies // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ this.inMemoryValueGenerationStrategies = new InMemoryValueGenerationStrategy[propertySpan]; this.inDatabaseValueGenerationStrategies = new InDatabaseValueGenerationStrategy[propertySpan]; boolean foundPreInsertGeneratedValues = false; boolean foundPreUpdateGeneratedValues = false; boolean foundPostInsertGeneratedValues = false; boolean foundPostUpdateGeneratedValues = false; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Iterator iter = persistentClass.getPropertyClosureIterator(); int i = 0; int tempVersionProperty = NO_VERSION_INDX; boolean foundCascade = false; boolean foundCollection = false; boolean foundMutable = false; boolean foundNonIdentifierPropertyNamedId = false; boolean foundInsertGeneratedValue = false; boolean foundUpdateGeneratedValue = false; boolean foundUpdateableNaturalIdProperty = false; while (iter.hasNext()) { Property prop = (Property) iter.next(); if (prop == persistentClass.getVersion()) { tempVersionProperty = i; properties[i] = PropertyFactory.buildVersionProperty( persister, sessionFactory, i, prop, instrumentationMetadata.isInstrumented()); } else { properties[i] = PropertyFactory.buildEntityBasedAttribute( persister, sessionFactory, i, prop, instrumentationMetadata.isInstrumented()); } if (prop.isNaturalIdentifier()) { naturalIdNumbers.add(i); if (prop.isUpdateable()) { foundUpdateableNaturalIdProperty = true; } } if ("id".equals(prop.getName())) { foundNonIdentifierPropertyNamedId = true; } // temporary ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ boolean lazy = prop.isLazy() && instrumentationMetadata.isInstrumented(); if (lazy) hasLazy = true; propertyLaziness[i] = lazy; propertyNames[i] = properties[i].getName(); propertyTypes[i] = properties[i].getType(); propertyNullability[i] = properties[i].isNullable(); propertyUpdateability[i] = properties[i].isUpdateable(); propertyInsertability[i] = properties[i].isInsertable(); propertyVersionability[i] = properties[i].isVersionable(); nonlazyPropertyUpdateability[i] = properties[i].isUpdateable() && !lazy; propertyCheckability[i] = propertyUpdateability[i] || (propertyTypes[i].isAssociationType() && ((AssociationType) propertyTypes[i]).isAlwaysDirtyChecked()); cascadeStyles[i] = properties[i].getCascadeStyle(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // generated value strategies // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GenerationStrategyPair pair = buildGenerationStrategyPair(sessionFactory, prop); inMemoryValueGenerationStrategies[i] = pair.getInMemoryStrategy(); inDatabaseValueGenerationStrategies[i] = pair.getInDatabaseStrategy(); if (pair.getInMemoryStrategy() != null) { final GenerationTiming timing = pair.getInMemoryStrategy().getGenerationTiming(); if (timing != GenerationTiming.NEVER) { final ValueGenerator generator = pair.getInMemoryStrategy().getValueGenerator(); if (generator != null) { // we have some level of generation indicated if (timing == GenerationTiming.INSERT) { foundPreInsertGeneratedValues = true; } else if (timing == GenerationTiming.ALWAYS) { foundPreInsertGeneratedValues = true; foundPreUpdateGeneratedValues = true; } } } } if (pair.getInDatabaseStrategy() != null) { final GenerationTiming timing = pair.getInDatabaseStrategy().getGenerationTiming(); if (timing == GenerationTiming.INSERT) { foundPostInsertGeneratedValues = true; } else if (timing == GenerationTiming.ALWAYS) { foundPostInsertGeneratedValues = true; foundPostUpdateGeneratedValues = true; } } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if (properties[i].isLazy()) { hasLazy = true; } if (properties[i].getCascadeStyle() != CascadeStyles.NONE) { foundCascade = true; } if (indicatesCollection(properties[i].getType())) { foundCollection = true; } if (propertyTypes[i].isMutable() && propertyCheckability[i]) { foundMutable = true; } mapPropertyToIndex(prop, i); i++; } if (naturalIdNumbers.size() == 0) { naturalIdPropertyNumbers = null; hasImmutableNaturalId = false; hasCacheableNaturalId = false; } else { naturalIdPropertyNumbers = ArrayHelper.toIntArray(naturalIdNumbers); hasImmutableNaturalId = !foundUpdateableNaturalIdProperty; hasCacheableNaturalId = persistentClass.getNaturalIdCacheRegionName() != null; } this.hasPreInsertGeneratedValues = foundPreInsertGeneratedValues; this.hasPreUpdateGeneratedValues = foundPreUpdateGeneratedValues; this.hasInsertGeneratedValues = foundPostInsertGeneratedValues; this.hasUpdateGeneratedValues = foundPostUpdateGeneratedValues; hasCascades = foundCascade; hasNonIdentifierPropertyNamedId = foundNonIdentifierPropertyNamedId; versionPropertyIndex = tempVersionProperty; hasLazyProperties = hasLazy; if (hasLazyProperties) LOG.lazyPropertyFetchingAvailable(name); lazy = persistentClass.isLazy() && ( // TODO: this disables laziness even in non-pojo entity modes: !persistentClass.hasPojoRepresentation() || !ReflectHelper.isFinalClass(persistentClass.getProxyInterface())); mutable = persistentClass.isMutable(); if (persistentClass.isAbstract() == null) { // legacy behavior (with no abstract attribute specified) isAbstract = persistentClass.hasPojoRepresentation() && ReflectHelper.isAbstractClass(persistentClass.getMappedClass()); } else { isAbstract = persistentClass.isAbstract().booleanValue(); if (!isAbstract && persistentClass.hasPojoRepresentation() && ReflectHelper.isAbstractClass(persistentClass.getMappedClass())) { LOG.entityMappedAsNonAbstract(name); } } selectBeforeUpdate = persistentClass.hasSelectBeforeUpdate(); dynamicUpdate = persistentClass.useDynamicUpdate(); dynamicInsert = persistentClass.useDynamicInsert(); polymorphic = persistentClass.isPolymorphic(); explicitPolymorphism = persistentClass.isExplicitPolymorphism(); inherited = persistentClass.isInherited(); superclass = inherited ? persistentClass.getSuperclass().getEntityName() : null; hasSubclasses = persistentClass.hasSubclasses(); optimisticLockStyle = persistentClass.getOptimisticLockStyle(); final boolean isAllOrDirty = optimisticLockStyle == OptimisticLockStyle.ALL || optimisticLockStyle == OptimisticLockStyle.DIRTY; if (isAllOrDirty && !dynamicUpdate) { throw new MappingException( "optimistic-lock=all|dirty requires dynamic-update=\"true\": " + name); } if (versionPropertyIndex != NO_VERSION_INDX && isAllOrDirty) { throw new MappingException( "version and optimistic-lock=all|dirty are not a valid combination : " + name); } hasCollections = foundCollection; hasMutableProperties = foundMutable; iter = persistentClass.getSubclassIterator(); while (iter.hasNext()) { subclassEntityNames.add(((PersistentClass) iter.next()).getEntityName()); } subclassEntityNames.add(name); if (persistentClass.hasPojoRepresentation()) { entityNameByInheritenceClassMap.put( persistentClass.getMappedClass(), persistentClass.getEntityName()); iter = persistentClass.getSubclassIterator(); while (iter.hasNext()) { final PersistentClass pc = (PersistentClass) iter.next(); entityNameByInheritenceClassMap.put(pc.getMappedClass(), pc.getEntityName()); } } entityMode = persistentClass.hasPojoRepresentation() ? EntityMode.POJO : EntityMode.MAP; final EntityTuplizerFactory entityTuplizerFactory = sessionFactory.getSettings().getEntityTuplizerFactory(); final String tuplizerClassName = persistentClass.getTuplizerImplClassName(entityMode); if (tuplizerClassName == null) { entityTuplizer = entityTuplizerFactory.constructDefaultTuplizer(entityMode, this, persistentClass); } else { entityTuplizer = entityTuplizerFactory.constructTuplizer(tuplizerClassName, this, persistentClass); } }
@SuppressWarnings({CompilerWarnings.UNCHECKED}) private void buildEntityMetadatas() throws Exception { SessionFactoryImpl sessionFactory = ((SessionFactoryImpl) this.entityManagerFactory.getSessionFactory()); Class<?> entityBindingMappedClass; Class<? extends SdcctEntity> entityMappedClass; String entityName, entityPropName, entityPropFieldName; EntityMetadata entityMetadata; Map<String, PropertyMetadata> entityPropMetadatas; IndexedTypeDescriptor indexedEntityDesc; Method entityPropGetterMethod; boolean entityIndexed, entityPropIndexed; PropertyDescriptor indexedEntityPropDesc; PropertyMetadata entityPropMetadata; BidiMap<Integer, String> entityPropOrder; String[] entityPropOrderNames; for (PersistentClass entityBinding : metadata.getEntityBindings()) { if (((entityBindingMappedClass = entityBinding.getMappedClass()) == null) || !SdcctEntity.class.isAssignableFrom(entityBindingMappedClass)) { continue; } entityPropMetadatas = (entityMetadata = new EntityMetadataImpl( (entityName = entityBinding.getEntityName()), (entityIndexed = (indexedEntityDesc = searchIntegrator.getIndexedTypeDescriptor( (entityMappedClass = ((Class<? extends SdcctEntity>) entityBindingMappedClass)))) .isIndexed()), entityMappedClass, entityBinding.getTable().getName())) .getProperties(); this.entityMetadatas.put( ((Class<? extends SdcctEntity>) entityMappedClass.getInterfaces()[0]), entityMetadata); for (Property entityProp : IteratorUtils.asIterable( IteratorUtils.chainedIterator( ((Iterator<Property>) entityBinding.getRootClass().getPropertyIterator()), ((Iterator<Property>) entityBinding.getPropertyIterator())))) { entityPropName = entityProp.getName(); entityPropGetterMethod = entityProp.getGetter(entityMappedClass).getMethod(); if (entityProp.getColumnSpan() == 0) { continue; } entityPropIndexed = (entityIndexed && entityPropGetterMethod.isAnnotationPresent(Fields.class) && ((indexedEntityPropDesc = indexedEntityDesc.getProperty(entityPropName)) != null) && !indexedEntityPropDesc.isId()); entityPropMetadatas.put( entityPropName, (entityPropMetadata = new PropertyMetadataImpl( entityPropName, entityPropIndexed, ((Column) entityProp.getColumnIterator().next()).getName(), entityProp.getType()))); if (entityPropIndexed) { for (Field entityPropFieldAnno : entityPropGetterMethod.getAnnotation(Fields.class).value()) { if (entityPropFieldAnno.analyze() == Analyze.NO) { continue; } entityPropFieldName = entityPropFieldAnno.name(); switch (entityPropFieldAnno.analyzer().definition()) { case DbAnalyzerNames.EDGE_NGRAM: entityPropMetadata.setEdgeNgramFieldName(entityPropFieldName); break; case DbAnalyzerNames.LOWERCASE: entityPropMetadata.setLowercaseFieldName(entityPropFieldName); break; case DbAnalyzerNames.NGRAM: entityPropMetadata.setNgramFieldName(entityPropFieldName); break; case DbAnalyzerNames.PHONETIC: entityPropMetadata.setPhoneticFieldName(entityPropFieldName); break; } } } } entityMetadata.setIdProperty( entityPropMetadatas.get(entityBinding.getIdentifierProperty().getName())); entityPropOrder = entityMetadata.getPropertyOrder(); entityPropOrderNames = sessionFactory.getEntityPersister(entityName).getPropertyNames(); for (int a = 0; a < entityPropOrderNames.length; a++) { entityPropOrder.put(a, entityPropOrderNames[a]); } } LOGGER.debug( String.format( "Processed metadata for %d entities: [%s]", this.entityMetadatas.size(), this.entityMetadatas .values() .stream() .map(NamedBean::getName) .collect(Collectors.joining(", ")))); }
public RevisionInfoConfigurationResult configure( Configuration cfg, ReflectionManager reflectionManager) { Iterator<PersistentClass> classes = (Iterator<PersistentClass>) cfg.getClassMappings(); boolean revisionEntityFound = false; RevisionInfoGenerator revisionInfoGenerator = null; Class<?> revisionInfoClass = null; while (classes.hasNext()) { PersistentClass pc = classes.next(); XClass clazz; try { clazz = reflectionManager.classForName(pc.getClassName(), this.getClass()); } catch (ClassNotFoundException e) { throw new MappingException(e); } RevisionEntity revisionEntity = clazz.getAnnotation(RevisionEntity.class); if (revisionEntity != null) { if (revisionEntityFound) { throw new MappingException("Only one entity may be annotated with @RevisionEntity!"); } // Checking if custom revision entity isn't audited if (clazz.getAnnotation(Audited.class) != null) { throw new MappingException("An entity annotated with @RevisionEntity cannot be audited!"); } revisionEntityFound = true; MutableBoolean revisionNumberFound = new MutableBoolean(); MutableBoolean revisionTimestampFound = new MutableBoolean(); MutableBoolean modifiedEntityNamesFound = new MutableBoolean(); searchForRevisionInfoCfg( clazz, reflectionManager, revisionNumberFound, revisionTimestampFound, modifiedEntityNamesFound); if (!revisionNumberFound.isSet()) { throw new MappingException( "An entity annotated with @RevisionEntity must have a field annotated " + "with @RevisionNumber!"); } if (!revisionTimestampFound.isSet()) { throw new MappingException( "An entity annotated with @RevisionEntity must have a field annotated " + "with @RevisionTimestamp!"); } revisionInfoEntityName = pc.getEntityName(); revisionInfoClass = pc.getMappedClass(); Class<? extends RevisionListener> revisionListenerClass = getRevisionListenerClass(revisionEntity.value()); revisionInfoTimestampType = pc.getProperty(revisionInfoTimestampData.getName()).getType(); if (globalCfg.isTrackEntitiesChangedInRevisionEnabled() || DefaultTrackingModifiedEntitiesRevisionEntity.class.isAssignableFrom( revisionInfoClass) || modifiedEntityNamesFound.isSet()) { // If tracking modified entities parameter is enabled, custom revision info entity is a // subtype // of DefaultTrackingModifiedEntitiesRevisionEntity class, or @ModifiedEntityNames // annotation is used. revisionInfoGenerator = new DefaultTrackingModifiedEntitiesRevisionInfoGenerator( revisionInfoEntityName, revisionInfoClass, revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate(), modifiedEntityNamesData); globalCfg.setTrackEntitiesChangedInRevisionEnabled(true); } else { revisionInfoGenerator = new DefaultRevisionInfoGenerator( revisionInfoEntityName, revisionInfoClass, revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate()); } } } // In case of a custom revision info generator, the mapping will be null. Document revisionInfoXmlMapping = null; Class<? extends RevisionListener> revisionListenerClass = getRevisionListenerClass(RevisionListener.class); if (revisionInfoGenerator == null) { if (globalCfg.isTrackEntitiesChangedInRevisionEnabled()) { revisionInfoClass = DefaultTrackingModifiedEntitiesRevisionEntity.class; revisionInfoEntityName = DefaultTrackingModifiedEntitiesRevisionEntity.class.getName(); revisionInfoGenerator = new DefaultTrackingModifiedEntitiesRevisionInfoGenerator( revisionInfoEntityName, revisionInfoClass, revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate(), modifiedEntityNamesData); } else { revisionInfoClass = DefaultRevisionEntity.class; revisionInfoGenerator = new DefaultRevisionInfoGenerator( revisionInfoEntityName, revisionInfoClass, revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate()); } revisionInfoXmlMapping = generateDefaultRevisionInfoXmlMapping(); } return new RevisionInfoConfigurationResult( revisionInfoGenerator, revisionInfoXmlMapping, new RevisionInfoQueryCreator( revisionInfoEntityName, revisionInfoIdData.getName(), revisionInfoTimestampData.getName(), isTimestampAsDate()), generateRevisionInfoRelationMapping(), new RevisionInfoNumberReader(revisionInfoClass, revisionInfoIdData), globalCfg.isTrackEntitiesChangedInRevisionEnabled() ? new ModifiedEntityNamesReader(revisionInfoClass, modifiedEntityNamesData) : null, revisionInfoEntityName, revisionInfoClass, revisionInfoTimestampData); }