public Task <object> ReadKeyAsync(DbDataReader dr, string[] aliases, ISessionImplementor session, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return(Task.FromCanceled <object>(cancellationToken)); } return(KeyType.NullSafeGetAsync(dr, aliases, session, null, cancellationToken)); }
/// <summary> /// Reads the Element from the DbDataReader. The DbDataReader will probably only contain /// the id of the Element. /// </summary> /// <remarks>See ReadElementIdentifier for an explanation of why this method will be depreciated.</remarks> public Task <object> ReadElementAsync(DbDataReader rs, object owner, string[] aliases, ISessionImplementor session, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return(Task.FromCanceled <object>(cancellationToken)); } return(ElementType.NullSafeGetAsync(rs, aliases, session, owner, cancellationToken)); }
private Mapping.Collection CreateArray(XmlNode node, string prefix, string path, PersistentClass owner, System.Type containingType, IDictionary <string, MetaAttribute> inheritedMetas) { Array array = new Array(owner); BindArray(node, array, prefix, path, containingType, inheritedMetas); return(array); }
private Mapping.Collection CreateArray(HbmArray arrayMapping, string prefix, string path, PersistentClass owner, System.Type containingType, IDictionary <string, MetaAttribute> inheritedMetas) { var array = new Array(owner); BindArray(arrayMapping, array, prefix, path, containingType, inheritedMetas); AddArraySecondPass(arrayMapping, array, inheritedMetas); return(array); }
private void AddArraySecondPass(HbmArray arrayMapping, Array model, IDictionary <string, MetaAttribute> inheritedMetas) { mappings.AddSecondPass(delegate(IDictionary <string, PersistentClass> persistentClasses) { PreCollectionSecondPass(model); BindArraySecondPass(arrayMapping, model, persistentClasses, inheritedMetas); PostCollectionSecondPass(model); }); }
/// <remarks> /// Called for arrays and primitive arrays /// </remarks> private void BindArray(XmlNode node, Array model, string prefix, string path, System.Type containingType, IDictionary <string, MetaAttribute> inheritedMetas) { BindCollection(node, model, prefix, path, containingType, inheritedMetas); XmlAttribute att = node.Attributes["element-class"]; if (att != null) { model.ElementClassName = GetQualifiedClassName(att.Value, mappings); } else { foreach (XmlNode subnode in node.ChildNodes) { // TODO NH: mmm.... the code below, maybe, must be resolved by SecondPass (not here) string name = subnode.LocalName; //.Name; //I am only concerned with elements that are from the nhibernate namespace if (subnode.NamespaceURI != Configuration.MappingSchemaXMLNS) { continue; } switch (name) { case "element": string typeName; XmlAttribute typeAttribute = subnode.Attributes["type"]; if (typeAttribute != null) { typeName = typeAttribute.Value; } else { throw new MappingException("type for <element> was not defined"); } IType type = TypeFactory.HeuristicType(typeName, null); if (type == null) { throw new MappingException("could not interpret type: " + typeName); } model.ElementClassName = type.ReturnedClass.AssemblyQualifiedName; break; case "one-to-many": case "many-to-many": case "composite-element": model.ElementClassName = GetQualifiedClassName(subnode.Attributes["class"].Value, mappings); break; } } } }
public Task BindSelectByUniqueKeyAsync( ISessionImplementor session, DbCommand selectCommand, IBinder binder, string[] suppliedPropertyNames, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return(Task.FromCanceled <object>(cancellationToken)); } return(binder.BindValuesAsync(selectCommand, cancellationToken)); }
public async Task <object> ReadIndexAsync(DbDataReader rs, string[] aliases, ISessionImplementor session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); object index = await(IndexType.NullSafeGetAsync(rs, aliases, session, null, cancellationToken)).ConfigureAwait(false); if (index == null) { throw new HibernateException("null index column for collection: " + role); } index = DecrementIndexByBase(index); return(index); }
/// <remarks> /// Called for arrays and primitive arrays /// </remarks> private void BindArray(HbmArray arrayMapping, Array model, string prefix, string path, System.Type containingType, IDictionary <string, MetaAttribute> inheritedMetas) { BindCollection(arrayMapping, model, prefix, path, containingType, inheritedMetas); var att = arrayMapping.elementclass; if (att != null) { model.ElementClassName = GetQualifiedClassName(att, mappings); } else { HbmElement element; HbmOneToMany oneToMany; HbmManyToMany manyToMany; HbmCompositeElement compositeElement; if ((element = arrayMapping.ElementRelationship as HbmElement) != null) { string typeName; var typeAttribute = element.Type; if (typeAttribute != null) { typeName = typeAttribute.name; } else { throw new MappingException("type for <element> was not defined"); } IType type = TypeFactory.HeuristicType(typeName, null); if (type == null) { throw new MappingException("could not interpret type: " + typeName); } model.ElementClassName = type.ReturnedClass.AssemblyQualifiedName; } else if ((oneToMany = arrayMapping.ElementRelationship as HbmOneToMany) != null) { model.ElementClassName = GetQualifiedClassName(oneToMany.@class, mappings); } else if ((manyToMany = arrayMapping.ElementRelationship as HbmManyToMany) != null) { model.ElementClassName = GetQualifiedClassName(manyToMany.@class, mappings); } else if ((compositeElement = arrayMapping.ElementRelationship as HbmCompositeElement) != null) { model.ElementClassName = GetQualifiedClassName(compositeElement.@class, mappings); } } }
private bool IndicatesCollection(IType type) { if (type.IsCollectionType) { return(true); } else if (type.IsComponentType) { IType[] subtypes = ((IAbstractComponentType)type).Subtypes; for (int i = 0; i < subtypes.Length; i++) { if (IndicatesCollection(subtypes[i])) { return(true); } } } return(false); }
protected Task <int> WriteElementToWhereAsync(DbCommand st, object elt, bool[] columnNullness, int i, ISessionImplementor session, CancellationToken cancellationToken) { if (elementIsPureFormula) { throw new AssertionFailure("cannot use a formula-based element in the where condition"); } if (cancellationToken.IsCancellationRequested) { return(Task.FromCanceled <int>(cancellationToken)); } return(InternalWriteElementToWhereAsync()); async Task <int> InternalWriteElementToWhereAsync() { var settable = Combine(elementColumnIsInPrimaryKey, columnNullness); await(ElementType.NullSafeSetAsync(st, elt, i, settable, session, cancellationToken)).ConfigureAwait(false); return(i + settable.Count(s => s)); } }
public AbstractCollectionPersister(Mapping.Collection collection, ISessionFactoryImplementor factory) { this.factory = factory; dialect = factory.Dialect; //sqlExceptionConverter = factory.SQLExceptionConverter; collectionType = collection.CollectionType; role = collection.Role; ownerClass = collection.OwnerClass; Alias alias = new Alias("__"); sqlOrderByString = collection.OrderBy; hasOrder = sqlOrderByString != null; sqlOrderByStringTemplate = hasOrder ? Template.RenderOrderByStringTemplate(sqlOrderByString, dialect) : null; sqlWhereString = collection.Where; hasWhere = sqlWhereString != null; sqlWhereStringTemplate = hasWhere ? Template.RenderWhereStringTemplate(sqlWhereString, dialect) : null; hasOrphanDelete = collection.OrphanDelete; batchSize = collection.BatchSize; cache = collection.Cache; keyType = collection.Key.Type; int keySpan = collection.Key.ColumnSpan; keyColumnNames = new string[keySpan]; string[] keyAliases = new string[keySpan]; int k = 0; foreach (Column col in collection.Key.ColumnCollection) { keyColumnNames[k] = col.GetQuotedName(dialect); keyAliases[k] = col.Alias(dialect); k++; } keyColumnAliases = alias.ToAliasStrings(keyAliases, dialect); //unquotedKeyColumnNames = StringHelper.Unquote( keyColumnAliases ); ISet distinctColumns = new HashedSet(); CheckColumnDuplication(distinctColumns, collection.Key.ColumnCollection); //isSet = collection.IsSet; //isSorted = collection.IsSorted; primitiveArray = collection.IsPrimitiveArray; array = collection.IsArray; IValue element = collection.Element; int elementSpan = element.ColumnSpan; ICollection iter = element.ColumnCollection; Table table = collection.CollectionTable; enableJoinedFetch = element.OuterJoinFetchSetting; elementType = element.Type; if (!collection.IsOneToMany) { CheckColumnDuplication(distinctColumns, element.ColumnCollection); } if (elementType.IsEntityType) { elementPersister = factory.GetPersister((( EntityType )elementType).AssociatedClass); } else { elementPersister = null; } qualifiedTableName = table.GetQualifiedName(dialect, factory.DefaultSchema); string[] aliases = new string[elementSpan]; elementColumnNames = new string[elementSpan]; int j = 0; foreach (Column col in iter) { elementColumnNames[j] = col.GetQuotedName(dialect); aliases[j] = col.Alias(dialect); j++; } elementColumnAliases = alias.ToAliasStrings(aliases, dialect); IType selectColumns; string[] selectType; hasIndex = collection.IsIndexed; if (hasIndex) { IndexedCollection indexedCollection = ( IndexedCollection )collection; indexType = indexedCollection.Index.Type; int indexSpan = indexedCollection.Index.ColumnSpan; indexColumnNames = new string[indexSpan]; string[] indexAliases = new string[indexSpan]; int i = 0; foreach (Column indexCol in indexedCollection.Index.ColumnCollection) { indexAliases[i] = indexCol.Alias(dialect); indexColumnNames[i] = indexCol.GetQuotedName(dialect); i++; } selectType = indexColumnNames; selectColumns = indexType; indexColumnAliases = alias.ToAliasStrings(indexAliases, dialect); CheckColumnDuplication(distinctColumns, indexedCollection.Index.ColumnCollection); } else { indexType = null; indexColumnNames = null; indexColumnAliases = null; selectType = elementColumnNames; selectColumns = elementType; } hasIdentifier = collection.IsIdentified; if (hasIdentifier) { if (collection.IsOneToMany) { throw new MappingException("one-to-many collections with identifiers are not supported."); } IdentifierCollection idColl = ( IdentifierCollection )collection; identifierType = idColl.Identifier.Type; Column col = null; foreach (Column column in idColl.Identifier.ColumnCollection) { col = column; break; } identifierColumnName = col.GetQuotedName(dialect); selectType = new string[] { identifierColumnName }; selectColumns = identifierType; identifierColumnAlias = alias.ToAliasString(col.Alias(dialect), dialect); unquotedIdentifierColumnName = identifierColumnAlias; identifierGenerator = idColl.Identifier.CreateIdentifierGenerator(dialect); CheckColumnDuplication(distinctColumns, idColl.Identifier.ColumnCollection); } else { identifierType = null; identifierColumnName = null; identifierColumnAlias = null; unquotedIdentifierColumnName = null; identifierGenerator = null; } rowSelectColumnNames = selectType; rowSelectType = selectColumns; sqlDeleteString = GenerateDeleteString(); sqlInsertRowString = GenerateInsertRowString(); sqlUpdateRowString = GenerateUpdateRowString(); sqlDeleteRowString = GenerateDeleteRowString(); isLazy = collection.IsLazy; isInverse = collection.IsInverse; if (collection.IsArray) { elementClass = (( Array )collection).ElementClass; } else { // for non-arrays, we don't need to know the element class elementClass = null; } initializer = CreateCollectionInitializer(factory); if (elementType.IsComponentType) { elementPropertyMapping = new CompositeElementPropertyMapping(elementColumnNames, ( IAbstractComponentType )elementType, factory); } else if (!elementType.IsEntityType) { elementPropertyMapping = new ElementPropertyMapping(elementColumnNames, elementType); } else { IClassPersister persister = factory.GetPersister((( EntityType )elementType).AssociatedClass); // Not all classpersisters implement IPropertyMapping! if (persister is IPropertyMapping) { elementPropertyMapping = ( IPropertyMapping )persister; } else { elementPropertyMapping = new ElementPropertyMapping(elementColumnNames, elementType); } } }
/// <remarks> /// Called for arrays and primitive arrays /// </remarks> private void BindArray(XmlNode node, Array model, string prefix, string path, System.Type containingType) { BindCollection(node, model, prefix, path, containingType); XmlAttribute att = node.Attributes["element-class"]; if (att != null) model.ElementClassName = GetQualifiedClassName(att.Value, mappings); else foreach (XmlNode subnode in node.ChildNodes) { // TODO NH: mmm.... the code below, maybe, must be resolved by SecondPass (not here) string name = subnode.LocalName; //.Name; //I am only concerned with elements that are from the nhibernate namespace if (subnode.NamespaceURI != Configuration.MappingSchemaXMLNS) continue; switch (name) { case "element": string typeName; XmlAttribute typeAttribute = subnode.Attributes["type"]; if (typeAttribute != null) typeName = typeAttribute.Value; else throw new MappingException("type for <element> was not defined"); IType type = TypeFactory.HeuristicType(typeName, null); if (type == null) throw new MappingException("could not interpret type: " + typeName); model.ElementClassName = type.ReturnedClass.AssemblyQualifiedName; break; case "one-to-many": case "many-to-many": case "composite-element": model.ElementClassName = GetQualifiedClassName(subnode.Attributes["class"].Value, mappings); break; } } }
private Mapping.Collection CreateArray(XmlNode node, string prefix, string path, PersistentClass owner, System.Type containingType) { Array array = new Array(owner); BindArray(node, array, prefix, path, containingType); return array; }
public EntityMetamodel(PersistentClass persistentClass, ISessionFactoryImplementor sessionFactory) { this.sessionFactory = sessionFactory; name = persistentClass.EntityName; rootName = persistentClass.RootClazz.EntityName; entityType = TypeFactory.ManyToOne(name); type = persistentClass.MappedClass; rootType = persistentClass.RootClazz.MappedClass; rootTypeAssemblyQualifiedName = rootType == null ? null : rootType.AssemblyQualifiedName; identifierProperty = PropertyFactory.BuildIdentifierProperty(persistentClass, sessionFactory.GetIdentifierGenerator(rootName)); versioned = persistentClass.IsVersioned; bool lazyAvailable = persistentClass.HasPocoRepresentation && FieldInterceptionHelper.IsInstrumented(persistentClass.MappedClass); bool hasLazy = false; propertySpan = persistentClass.PropertyClosureSpan; properties = new StandardProperty[propertySpan]; List <int> naturalIdNumbers = new List <int>(); propertyNames = new string[propertySpan]; propertyTypes = new IType[propertySpan]; propertyUpdateability = new bool[propertySpan]; propertyInsertability = new bool[propertySpan]; insertInclusions = new ValueInclusion[propertySpan]; updateInclusions = new ValueInclusion[propertySpan]; nonlazyPropertyUpdateability = new bool[propertySpan]; propertyCheckability = new bool[propertySpan]; propertyNullability = new bool[propertySpan]; propertyVersionability = new bool[propertySpan]; propertyLaziness = new bool[propertySpan]; cascadeStyles = new CascadeStyle[propertySpan]; int i = 0; int tempVersionProperty = NoVersionIndex; bool foundCascade = false; bool foundCollection = false; bool foundMutable = false; bool foundInsertGeneratedValue = false; bool foundUpdateGeneratedValue = false; bool foundNonIdentifierPropertyNamedId = false; HasPocoRepresentation = persistentClass.HasPocoRepresentation; // NH: WARNING if we have to disable lazy/unproxy properties we have to do it in the whole process. lazy = persistentClass.IsLazy && (!persistentClass.HasPocoRepresentation || !ReflectHelper.IsFinalClass(persistentClass.ProxyInterface)); lazyAvailable &= lazy; // <== Disable lazy properties if the class is marked with lazy=false bool hadLazyProperties = false; bool hadNoProxyRelations = false; foreach (Mapping.Property prop in persistentClass.PropertyClosureIterator) { if (prop.IsLazy) { hadLazyProperties = true; } if (prop.UnwrapProxy) { hadNoProxyRelations = true; } // NH: A lazy property is a simple property marked with lazy=true bool islazyProperty = prop.IsLazy && lazyAvailable && (!prop.IsEntityRelation || prop.UnwrapProxy); // NH: A Relation (in this case many-to-one or one-to-one) marked as "no-proxy" var isUnwrapProxy = prop.UnwrapProxy && lazyAvailable; if (islazyProperty || isUnwrapProxy) { // NH: verify property proxiability var getter = prop.GetGetter(persistentClass.MappedClass); if (getter.Method == null || getter.Method.IsDefined(typeof(CompilerGeneratedAttribute), false) == false) { log.ErrorFormat("Lazy or no-proxy property {0}.{1} is not an auto property, which may result in uninitialized property access", persistentClass.EntityName, prop.Name); } } if (prop == persistentClass.Version) { tempVersionProperty = i; properties[i] = PropertyFactory.BuildVersionProperty(prop, islazyProperty); } else { properties[i] = PropertyFactory.BuildStandardProperty(prop, islazyProperty); } if (prop.IsNaturalIdentifier) { naturalIdNumbers.Add(i); } if ("id".Equals(prop.Name)) { foundNonIdentifierPropertyNamedId = true; } if (islazyProperty) { hasLazy = true; } if (isUnwrapProxy) { hasUnwrapProxyForProperties = true; } propertyLaziness[i] = islazyProperty; propertyNames[i] = properties[i].Name; propertyTypes[i] = properties[i].Type; propertyNullability[i] = properties[i].IsNullable; propertyUpdateability[i] = properties[i].IsUpdateable; propertyInsertability[i] = properties[i].IsInsertable; insertInclusions[i] = DetermineInsertValueGenerationType(prop, properties[i]); updateInclusions[i] = DetermineUpdateValueGenerationType(prop, properties[i]); propertyVersionability[i] = properties[i].IsVersionable; nonlazyPropertyUpdateability[i] = properties[i].IsUpdateable && !islazyProperty; propertyCheckability[i] = propertyUpdateability[i] || (propertyTypes[i].IsAssociationType && ((IAssociationType)propertyTypes[i]).IsAlwaysDirtyChecked); cascadeStyles[i] = properties[i].CascadeStyle; if (properties[i].IsLazy) { hasLazy = true; } if (properties[i].CascadeStyle != CascadeStyle.None) { foundCascade = true; } if (IndicatesCollection(properties[i].Type)) { foundCollection = true; } if (propertyTypes[i].IsMutable && propertyCheckability[i]) { foundMutable = true; } if (insertInclusions[i] != ValueInclusion.None) { foundInsertGeneratedValue = true; } if (updateInclusions[i] != ValueInclusion.None) { foundUpdateGeneratedValue = true; } MapPropertyToIndex(prop, i); i++; } if (naturalIdNumbers.Count == 0) { naturalIdPropertyNumbers = null; } else { naturalIdPropertyNumbers = naturalIdNumbers.ToArray(); } hasCascades = foundCascade; hasInsertGeneratedValues = foundInsertGeneratedValue; hasUpdateGeneratedValues = foundUpdateGeneratedValue; hasNonIdentifierPropertyNamedId = foundNonIdentifierPropertyNamedId; versionPropertyIndex = tempVersionProperty; hasLazyProperties = hasLazy; if (hadLazyProperties && !hasLazy) { log.WarnFormat("Disabled lazy property fetching for {0} because it does not support lazy at the entity level", name); } if (hasLazy) { log.Info("lazy property fetching available for: " + name); } if (hadNoProxyRelations && !hasUnwrapProxyForProperties) { log.WarnFormat("Disabled ghost property fetching for {0} because it does not support lazy at the entity level", name); } if (hasUnwrapProxyForProperties) { log.Info("no-proxy property fetching available for: " + name); } mutable = persistentClass.IsMutable; if (!persistentClass.IsAbstract.HasValue) { // legacy behavior (with no abstract attribute specified) isAbstract = persistentClass.HasPocoRepresentation && ReflectHelper.IsAbstractClass(persistentClass.MappedClass); } else { isAbstract = persistentClass.IsAbstract.Value; if (!isAbstract && persistentClass.HasPocoRepresentation && ReflectHelper.IsAbstractClass(persistentClass.MappedClass)) { log.Warn("entity [" + type.FullName + "] is abstract-class/interface explicitly mapped as non-abstract; be sure to supply entity-names"); } } selectBeforeUpdate = persistentClass.SelectBeforeUpdate; dynamicUpdate = persistentClass.DynamicUpdate; dynamicInsert = persistentClass.DynamicInsert; polymorphic = persistentClass.IsPolymorphic; explicitPolymorphism = persistentClass.IsExplicitPolymorphism; inherited = persistentClass.IsInherited; superclass = inherited ? persistentClass.Superclass.EntityName : null; superclassType = inherited ? persistentClass.Superclass.MappedClass : null; hasSubclasses = persistentClass.HasSubclasses; optimisticLockMode = persistentClass.OptimisticLockMode; if (optimisticLockMode > Versioning.OptimisticLock.Version && !dynamicUpdate) { throw new MappingException("optimistic-lock setting requires dynamic-update=\"true\": " + type.FullName); } hasCollections = foundCollection; hasMutableProperties = foundMutable; foreach (Subclass obj in persistentClass.SubclassIterator) { subclassEntityNames.Add(obj.EntityName); } subclassEntityNames.Add(name); EntityMode = persistentClass.HasPocoRepresentation ? EntityMode.Poco : EntityMode.Map; var entityTuplizerFactory = new EntityTuplizerFactory(); var tuplizerClassName = persistentClass.GetTuplizerImplClassName(EntityMode); Tuplizer = tuplizerClassName == null ? entityTuplizerFactory.BuildDefaultEntityTuplizer(EntityMode, this, persistentClass) : entityTuplizerFactory.BuildEntityTuplizer(tuplizerClassName, this, persistentClass); }
private Mapping.Collection CreateArray(HbmArray arrayMapping, string prefix, string path, PersistentClass owner, System.Type containingType, IDictionary<string, MetaAttribute> inheritedMetas) { var array = new Array(owner); BindArray(arrayMapping, array, prefix, path, containingType, inheritedMetas); AddArraySecondPass(arrayMapping, array, inheritedMetas); return array; }
private void AddPrimitiveArraySecondPass(HbmPrimitiveArray primitiveArrayMapping, Array model, IDictionary<string, MetaAttribute> inheritedMetas) { mappings.AddSecondPass(delegate(IDictionary<string, PersistentClass> persistentClasses) { PreCollectionSecondPass(model); BindPrimitiveArraySecondPass(primitiveArrayMapping, model, persistentClasses, inheritedMetas); PostCollectionSecondPass(model); }); }
/// <remarks> /// Called for arrays and primitive arrays /// </remarks> private void BindArray(HbmArray arrayMapping, Array model, string prefix, string path, System.Type containingType, IDictionary<string, MetaAttribute> inheritedMetas) { BindCollection(arrayMapping, model, prefix, path, containingType, inheritedMetas); var att = arrayMapping.elementclass; if (att != null) model.ElementClassName = GetQualifiedClassName(att, mappings); else { HbmElement element; HbmOneToMany oneToMany; HbmManyToMany manyToMany; HbmCompositeElement compositeElement; if((element = arrayMapping.ElementRelationship as HbmElement) != null) { string typeName; var typeAttribute = element.Type; if (typeAttribute != null) typeName = typeAttribute.name; else throw new MappingException("type for <element> was not defined"); IType type = TypeFactory.HeuristicType(typeName, null); if (type == null) throw new MappingException("could not interpret type: " + typeName); model.ElementClassName = type.ReturnedClass.AssemblyQualifiedName; } else if((oneToMany = arrayMapping.ElementRelationship as HbmOneToMany) != null) { model.ElementClassName = GetQualifiedClassName(oneToMany.@class, mappings); } else if ((manyToMany = arrayMapping.ElementRelationship as HbmManyToMany) != null) { model.ElementClassName = GetQualifiedClassName(manyToMany.@class, mappings); } else if ((compositeElement = arrayMapping.ElementRelationship as HbmCompositeElement) != null) { model.ElementClassName = GetQualifiedClassName(compositeElement.@class, mappings); } } }
/// <remarks> /// Called for arrays and primitive arrays /// </remarks> public static void BindArray( XmlNode node, Array model, string prefix, string path, Mappings mappings ) { BindCollection( node, model, prefix, path, mappings ); XmlAttribute att = node.Attributes[ "element-class" ]; if( att != null ) { model.ElementClass = ClassForNameChecked( att.Value, mappings, "could not find element class: {0}" ); } else { foreach( XmlNode subnode in node.ChildNodes ) { string name = subnode.LocalName; //.Name; //I am only concerned with elements that are from the nhibernate namespace if( subnode.NamespaceURI != Configuration.MappingSchemaXMLNS ) { continue; } switch( name ) { case "element": IType type = GetTypeFromXML( subnode ); model.ElementClass = type.ReturnedClass; break; case "one-to-many": case "many-to-many": case "composite-element": model.ElementClass = ClassForNameChecked( subnode.Attributes[ "class" ].Value, mappings, "element class not found: {0}" ); break; } } } }
public override Mapping.Collection Create( XmlNode node, string prefix, string path, PersistentClass owner, Mappings mappings ) { Array array = new Array( owner ); Binder.BindArray( node, array, prefix, path, mappings ); return array; }
private Mapping.Collection CreateArray(XmlNode node, string prefix, string path, PersistentClass owner, System.Type containingType, IDictionary<string, MetaAttribute> inheritedMetas) { Array array = new Array(owner); BindArray(node, array, prefix, path, containingType, inheritedMetas); return array; }
/// <remarks> /// Called for all collections. <paramref name="containingType" /> parameter /// was added in NH to allow for reflection related to generic types. /// </remarks> private void BindCollection(ICollectionPropertiesMapping collectionMapping, Mapping.Collection model, string className, string path, System.Type containingType, IDictionary <string, MetaAttribute> inheritedMetas) { // ROLENAME model.Role = path; model.IsInverse = collectionMapping.Inverse; model.IsMutable = collectionMapping.Mutable; model.IsOptimisticLocked = collectionMapping.OptimisticLock; model.OrderBy = collectionMapping.OrderBy; model.Where = collectionMapping.Where; if (collectionMapping.BatchSize.HasValue) { model.BatchSize = collectionMapping.BatchSize.Value; } // PERSISTER if (!string.IsNullOrEmpty(collectionMapping.PersisterQualifiedName)) { model.CollectionPersisterClass = ClassForNameChecked(collectionMapping.PersisterQualifiedName, mappings, "could not instantiate collection persister class: {0}"); } if (!string.IsNullOrEmpty(collectionMapping.CollectionType)) { TypeDef typeDef = mappings.GetTypeDef(collectionMapping.CollectionType); if (typeDef != null) { model.TypeName = typeDef.TypeClass; model.TypeParameters = typeDef.Parameters; } else { model.TypeName = FullQualifiedClassName(collectionMapping.CollectionType, mappings); } } // FETCH STRATEGY InitOuterJoinFetchSetting(collectionMapping, model); // LAZINESS InitLaziness(collectionMapping, model); var oneToManyMapping = collectionMapping.ElementRelationship as HbmOneToMany; if (oneToManyMapping != null) { var oneToMany = new OneToMany(model.Owner); model.Element = oneToMany; BindOneToMany(oneToManyMapping, oneToMany); //we have to set up the table later!! yuck } else { //TABLE string tableName = !string.IsNullOrEmpty(collectionMapping.Table) ? mappings.NamingStrategy.TableName(collectionMapping.Table) : mappings.NamingStrategy.PropertyToTableName(className, path); string schema = string.IsNullOrEmpty(collectionMapping.Schema) ? mappings.SchemaName : collectionMapping.Schema; string catalog = string.IsNullOrEmpty(collectionMapping.Catalog) ? mappings.CatalogName : collectionMapping.Catalog; // TODO NH : add schema-action to the xsd model.CollectionTable = mappings.AddTable(schema, catalog, tableName, collectionMapping.Subselect, false, "all"); log.InfoFormat("Mapping collection: {0} -> {1}", model.Role, model.CollectionTable.Name); } //SORT var sortedAtt = collectionMapping.Sort; // unsorted, natural, comparator.class.name if (string.IsNullOrEmpty(sortedAtt) || sortedAtt.Equals("unsorted")) { model.IsSorted = false; } else { model.IsSorted = true; if (!sortedAtt.Equals("natural")) { string comparatorClassName = FullQualifiedClassName(sortedAtt, mappings); model.ComparerClassName = comparatorClassName; } } //ORPHAN DELETE (used for programmer error detection) var cascadeAtt = collectionMapping.Cascade; if (!string.IsNullOrEmpty(cascadeAtt) && cascadeAtt.IndexOf("delete-orphan") >= 0) { model.HasOrphanDelete = true; } // GENERIC bool?isGeneric = collectionMapping.Generic; System.Type collectionType = null; if (!isGeneric.HasValue && containingType != null) { collectionType = GetPropertyType(containingType, collectionMapping.Name, collectionMapping.Access); isGeneric = collectionType.IsGenericType; } model.IsGeneric = isGeneric ?? false; if (model.IsGeneric) { // Determine the generic arguments using reflection if (collectionType == null) { collectionType = GetPropertyType(containingType, collectionMapping.Name, collectionMapping.Access); } System.Type[] genericArguments = collectionType.GetGenericArguments(); model.GenericArguments = genericArguments; } // CUSTOM SQL HandleCustomSQL(collectionMapping, model); if (collectionMapping.SqlLoader != null) { model.LoaderName = collectionMapping.SqlLoader.queryref; } new FiltersBinder(model, Mappings).Bind(collectionMapping.Filters); var key = collectionMapping.Key; if (key != null) { model.ReferencedPropertyName = key.propertyref; } }
/// <remarks> /// Called for all collections. <paramref name="containingType" /> parameter /// was added in NH to allow for reflection related to generic types. /// </remarks> private void BindCollection(XmlNode node, Mapping.Collection model, string className, string path, System.Type containingType, IDictionary <string, MetaAttribute> inheritedMetas) { // ROLENAME model.Role = StringHelper.Qualify(className, path); // TODO: H3.1 has just collection.setRole(path) here - why? XmlAttribute inverseNode = node.Attributes["inverse"]; if (inverseNode != null) { model.IsInverse = StringHelper.BooleanValue(inverseNode.Value); } // TODO: H3.1 - not ported: mutable XmlAttribute olNode = node.Attributes["optimistic-lock"]; model.IsOptimisticLocked = olNode == null || "true".Equals(olNode.Value); XmlAttribute orderNode = node.Attributes["order-by"]; if (orderNode != null) { model.OrderBy = orderNode.Value; } XmlAttribute whereNode = node.Attributes["where"]; if (whereNode != null) { model.Where = whereNode.Value; } XmlAttribute batchNode = node.Attributes["batch-size"]; if (batchNode != null) { model.BatchSize = int.Parse(batchNode.Value); } // PERSISTER XmlAttribute persisterNode = node.Attributes["persister"]; if (persisterNode == null) { //persister = CollectionPersisterImpl.class; } else { model.CollectionPersisterClass = ClassForNameChecked( persisterNode.Value, mappings, "could not instantiate collection persister class: {0}"); } XmlAttribute typeNode = node.Attributes["collection-type"]; if (typeNode != null) { string typeName = typeNode.Value; TypeDef typeDef = mappings.GetTypeDef(typeName); if (typeDef != null) { model.TypeName = typeDef.TypeClass; model.TypeParameters = typeDef.Parameters; } else { model.TypeName = FullQualifiedClassName(typeName, mappings); } } // FETCH STRATEGY InitOuterJoinFetchSetting(node, model); if ("subselect".Equals(XmlHelper.GetAttributeValue(node, "fetch"))) { model.IsSubselectLoadable = true; model.Owner.HasSubselectLoadableCollections = true; } // LAZINESS InitLaziness(node, model, "true", mappings.DefaultLazy); XmlAttribute lazyNode = node.Attributes["lazy"]; if (lazyNode != null && "extra".Equals(lazyNode.Value)) { model.IsLazy = true; model.ExtraLazy = true; } XmlNode oneToManyNode = node.SelectSingleNode(HbmConstants.nsOneToMany, namespaceManager); if (oneToManyNode != null) { OneToMany oneToMany = new OneToMany(model.Owner); model.Element = oneToMany; BindOneToMany(oneToManyNode, oneToMany); //we have to set up the table later!! yuck } else { //TABLE XmlAttribute tableNode = node.Attributes["table"]; string tableName; if (tableNode != null) { tableName = mappings.NamingStrategy.TableName(tableNode.Value); } else { tableName = mappings.NamingStrategy.PropertyToTableName(className, path); } XmlAttribute schemaNode = node.Attributes["schema"]; string schema = schemaNode == null ? mappings.SchemaName : schemaNode.Value; XmlAttribute catalogNode = node.Attributes["catalog"]; string catalog = catalogNode == null ? mappings.CatalogName : catalogNode.Value; XmlAttribute actionNode = node.Attributes["schema-action"]; string action = actionNode == null ? "all" : actionNode.Value; model.CollectionTable = mappings.AddTable(schema, catalog, tableName, null, false, action); log.InfoFormat("Mapping collection: {0} -> {1}", model.Role, model.CollectionTable.Name); } //SORT XmlAttribute sortedAtt = node.Attributes["sort"]; // unsorted, natural, comparator.class.name if (sortedAtt == null || sortedAtt.Value.Equals("unsorted")) { model.IsSorted = false; } else { model.IsSorted = true; if (!sortedAtt.Value.Equals("natural")) { string comparatorClassName = FullQualifiedClassName(sortedAtt.Value, mappings); model.ComparerClassName = comparatorClassName; } } //ORPHAN DELETE (used for programmer error detection) XmlAttribute cascadeAtt = node.Attributes["cascade"]; if (cascadeAtt != null && cascadeAtt.Value.IndexOf("delete-orphan") >= 0) { model.HasOrphanDelete = true; } bool?isGeneric = null; XmlAttribute genericAtt = node.Attributes["generic"]; if (genericAtt != null) { isGeneric = bool.Parse(genericAtt.Value); } System.Type collectionType = null; if (!isGeneric.HasValue && containingType != null) { collectionType = GetPropertyType(node, containingType, GetPropertyName(node)); isGeneric = collectionType.IsGenericType; } model.IsGeneric = isGeneric ?? false; if (model.IsGeneric) { // Determine the generic arguments using reflection if (collectionType == null) { collectionType = GetPropertyType(node, containingType, GetPropertyName(node)); } System.Type[] genericArguments = collectionType.GetGenericArguments(); model.GenericArguments = genericArguments; } HandleCustomSQL(node, model); //set up second pass if (model is List) { AddListSecondPass(node, (List)model, inheritedMetas); } else if (model is Map) { AddMapSecondPass(node, (Map)model, inheritedMetas); } else if (model is Set) { AddSetSecondPass(node, (Set)model, inheritedMetas); } else if (model is IdentifierCollection) { AddIdentifierCollectionSecondPass(node, (IdentifierCollection)model, inheritedMetas); } else { AddCollectionSecondPass(node, model, inheritedMetas); } foreach (XmlNode filter in node.SelectNodes(HbmConstants.nsFilter, namespaceManager)) { ParseFilter(filter, model); } XmlNode loader = node.SelectSingleNode(HbmConstants.nsLoader, namespaceManager); if (loader != null) { model.LoaderName = XmlHelper.GetAttributeValue(loader, "query-ref"); } XmlNode key = node.SelectSingleNode(HbmConstants.nsKey, namespaceManager); if (key != null) { model.ReferencedPropertyName = XmlHelper.GetAttributeValue(key, "property-ref"); } }