public static IEntityPersister GetEntityPersister(this ISession session, Object entity, out EntityEntry oldEntry) { ISessionImplementor sessionImpl = session.GetSessionImplementation(); IPersistenceContext persistenceContext = sessionImpl.PersistenceContext; oldEntry = persistenceContext.GetEntry(entity); if ((oldEntry == null) && (entity is INHibernateProxy)) { INHibernateProxy proxy = entity as INHibernateProxy; Object obj = sessionImpl.PersistenceContext.Unproxy(proxy); oldEntry = sessionImpl.PersistenceContext.GetEntry(obj); } string className; if (oldEntry != null) { className = oldEntry.EntityName; } else { className = sessionImpl.Factory.GetClassMetadata(entity.GetType()).EntityName; } IEntityPersister persister = sessionImpl.Factory.GetEntityPersister(className); return(persister); }
private void ListDirtyProperties(object entity) { string className = NHibernateProxyHelper.GuessClass(entity).FullName; ISessionImplementor sessionImpl = m_Session.GetSessionImplementation(); IEntityPersister persister = sessionImpl.Factory.GetEntityPersister(className); EntityEntry oldEntry = sessionImpl.PersistenceContext.GetEntry(entity); if (oldEntry == null) { INHibernateProxy proxy = entity as INHibernateProxy; object obj = proxy != null?sessionImpl.PersistenceContext.Unproxy(proxy) : entity; oldEntry = sessionImpl.PersistenceContext.GetEntry(obj); } object[] oldState = oldEntry.LoadedState; object[] currentState = persister.GetPropertyValues(entity, sessionImpl.EntityMode); int[] dirtyProperties = persister.FindDirty(currentState, oldState, entity, sessionImpl); foreach (int index in dirtyProperties) { string msg = string.Format( "Dirty property {0}.{1} was {2}, is {3}.", className, persister.PropertyNames[index], oldState[index] ?? "null", currentState[index] ?? "null"); DirtyProps.Add(msg); } }
public override bool IsEqual(object x, object y, ISessionFactoryImplementor factory) { IEntityPersister persister = factory.GetEntityPersister(associatedEntityName); if (!persister.CanExtractIdOutOfEntity) { return(base.IsEqual(x, y)); } object xid; if (x.IsProxy()) { INHibernateProxy proxy = x as INHibernateProxy; xid = proxy.HibernateLazyInitializer.Identifier; } else { xid = persister.GetIdentifier(x); } object yid; if (y.IsProxy()) { INHibernateProxy proxy = y as INHibernateProxy; yid = proxy.HibernateLazyInitializer.Identifier; } else { yid = persister.GetIdentifier(y); } return(persister.IdentifierType.IsEqual(xid, yid, factory)); }
public static object GetOriginalEntityProperty(this ISession session, object entity, string propertyName) { ISessionImplementor sessionImpl = session.GetSessionImplementation(); IPersistenceContext persistenceContext = sessionImpl.PersistenceContext; EntityEntry oldEntry = persistenceContext.GetEntry(entity); if ((oldEntry == null) && (entity is INHibernateProxy)) { INHibernateProxy proxy = entity as INHibernateProxy; object obj = sessionImpl.PersistenceContext.Unproxy(proxy); oldEntry = sessionImpl.PersistenceContext.GetEntry(obj); } if (oldEntry == null) { return(null); } string className = oldEntry.EntityName; IEntityPersister persister = sessionImpl.Factory.GetEntityPersister(className); object[] oldState = oldEntry.LoadedState; object[] currentState = persister.GetPropertyValues(entity); int[] dirtyProps = persister.FindDirty(currentState, oldState, entity, sessionImpl); int index = Array.IndexOf(persister.PropertyNames, propertyName); bool isDirty = (dirtyProps != null) && (Array.IndexOf(dirtyProps, index) != -1); return(isDirty ? oldState[index] : currentState[index]); }
public virtual bool Contains(object collection, object childObject, ISessionImplementor session) { // we do not have to worry about queued additions to uninitialized // collections, since they can only occur for inverse collections! IEnumerable elems = GetElementsIterator(collection, session); foreach (object elem in elems) { object element = elem; // worrying about proxies is perhaps a little bit of overkill here... if (element.IsProxy()) { INHibernateProxy proxy = element as INHibernateProxy; ILazyInitializer li = proxy.HibernateLazyInitializer; if (!li.IsUninitialized) { element = li.GetImplementation(); } } if (element == childObject) { return(true); } } return(false); }
public static Boolean IsDirtyEntity(this ISession session, Object entity) { ISessionImplementor sessionImpl = session.GetSessionImplementation(); IPersistenceContext persistenceContext = sessionImpl.PersistenceContext; EntityEntry oldEntry = persistenceContext.GetEntry(entity); if ((oldEntry == null) && (entity is INHibernateProxy)) { INHibernateProxy proxy = entity as INHibernateProxy; Object obj = sessionImpl.PersistenceContext.Unproxy(proxy); oldEntry = sessionImpl.PersistenceContext.GetEntry(obj); } if (oldEntry == null) { return(false); } string className = oldEntry.EntityName; IEntityPersister persister = sessionImpl.Factory.GetEntityPersister(className); Object[] oldState = oldEntry.LoadedState; if (oldState == null) { return(false); } Object[] currentState = persister.GetPropertyValues(entity, sessionImpl.EntityMode); Int32[] dirtyProps = oldState.Select((o, i) => ValuesAreEqual(oldState[i], currentState[i]) ? -1 : i).Where(x => x >= 0).ToArray(); return(dirtyProps != null && dirtyProps.Length > 0); }
/// <summary> /// Gets the <see cref="LazyInitializer"/> that is used by the Proxy. /// </summary> /// <param name="proxy">The Proxy object</param> /// <returns> /// A reference to <see cref="LazyInitializer"/> that contains the details /// of the Proxied object. /// </returns> public static LazyInitializer GetLazyInitializer( INHibernateProxy proxy ) { // have to hard code in "__interceptor" - very dependant on them not changing their // implementation - TODO: email Hammet about this - or at least to provide a static // field object fieldValue = proxy.GetType().GetField( "__interceptor" ).GetValue( proxy ); return ( LazyInitializer ) fieldValue; }
/// <summary> /// Gets the <see cref="LazyInitializer"/> that is used by the Proxy. /// </summary> /// <param name="proxy">The Proxy object</param> /// <returns> /// A reference to <see cref="LazyInitializer"/> that contains the details /// of the Proxied object. /// </returns> public static LazyInitializer GetLazyInitializer(INHibernateProxy proxy) { // have to hard code in "__interceptor" - very dependant on them not changing their // implementation - TODO: email Hammet about this - or at least to provide a static // field object fieldValue = proxy.GetType().GetField("__interceptor").GetValue(proxy); return(( LazyInitializer )fieldValue); }
private object InitializeOrGetAssociation(INHibernateProxy value, string fieldName) { if (value.HibernateLazyInitializer.IsUninitialized) { value.HibernateLazyInitializer.Initialize(); value.HibernateLazyInitializer.Unwrap = true; // means that future Load/Get from the session will get the implementation loadedUnwrapProxyFieldNames.Add(fieldName); } return(value.HibernateLazyInitializer.GetImplementation(session)); }
public static T Unproxy <T>(this T document) where T : SiteEntity { INHibernateProxy proxy = document as INHibernateProxy; if (proxy != null) { return((T)proxy.HibernateLazyInitializer.GetImplementation()); } return((T)document); }
public TEntity UnProxy <TEntity>(TEntity entity) { INHibernateProxy proxy = entity as INHibernateProxy; if (proxy != null) { return((TEntity)proxy.HibernateLazyInitializer.GetImplementation()); } return(entity); }
public override string BestGuessEntityName(object entity) { using (new SessionIdLoggingContext(SessionId)) { if (entity.IsProxy()) { INHibernateProxy proxy = entity as INHibernateProxy; entity = proxy.HibernateLazyInitializer.GetImplementation(); } return(GuessEntityName(entity)); } }
void IGraph.SetSource(object source) { if (source is INHibernateProxy) { INHibernateProxy proxy = (INHibernateProxy)source; _source = proxy.HibernateLazyInitializer.GetImplementation(); } else { _source = source; } }
/// <summary> /// Convenience method to figure out the underlying type for the object regardless of it /// is a Proxied object or the real object. /// </summary> /// <param name="obj">The object to get the type of.</param> /// <returns>The Underlying Type for the object regardless of if it is a Proxy.</returns> public static System.Type GetClass(object obj) { if (obj is INHibernateProxy) { INHibernateProxy proxy = ( INHibernateProxy )obj; LazyInitializer li = NHibernateProxyHelper.GetLazyInitializer(proxy); return(li.PersistentClass); } else { return(obj.GetType()); } }
public static object GetIdentifier(object obj, IClassPersister persister) { if (obj is INHibernateProxy) { INHibernateProxy proxy = ( INHibernateProxy )obj; LazyInitializer li = GetLazyInitializer(proxy); return(li.Identifier); } else { return(persister.GetIdentifier(obj)); } }
/// <summary> /// Get the class of an instance or the underlying class of a proxy (without initializing the proxy!). /// It is almost always better to use the entity name! /// </summary> /// <param name="obj">The object to get the type of.</param> /// <returns>The Underlying Type for the object regardless of if it is a Proxy.</returns> public static System.Type GetClassWithoutInitializingProxy(object obj) { if (obj.IsProxy()) { INHibernateProxy proxy = obj as INHibernateProxy; return(proxy.HibernateLazyInitializer.PersistentClass); } else { return(obj.GetType()); } }
/// <summary> /// Determine if the object already exists in the database, using a "best guess" /// </summary> private async Task <bool> IsNullifiableAsync(string entityName, object obj, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); //if (obj == org.hibernate.intercept.LazyPropertyInitializer_Fields.UNFETCHED_PROPERTY) // return false; //this is kinda the best we can do... if (obj.IsProxy()) { INHibernateProxy proxy = obj as INHibernateProxy; // if its an uninitialized proxy it can't be transient ILazyInitializer li = proxy.HibernateLazyInitializer; if (li.GetImplementation(session) == null) { return(false); // ie. we never have to null out a reference to // an uninitialized proxy } else { //unwrap it obj = await(li.GetImplementationAsync(cancellationToken)).ConfigureAwait(false); } } // if it was a reference to self, don't need to nullify // unless we are using native id generation, in which // case we definitely need to nullify if (obj == self) { // TODO H3.2: Different behaviour //return isEarlyInsert || (isDelete && session.Factory.Dialect.HasSelfReferentialForeignKeyBug); return(isEarlyInsert || isDelete); } // See if the entity is already bound to this session, if not look at the // entity identifier and assume that the entity is persistent if the // id is not "unsaved" (that is, we rely on foreign keys to keep // database integrity) EntityEntry entityEntry = session.PersistenceContext.GetEntry(obj); if (entityEntry == null) { return(await(IsTransientSlowAsync(entityName, obj, session, cancellationToken)).ConfigureAwait(false)); } else { return(entityEntry.IsNullifiable(isEarlyInsert, session)); } }
/// <summary> /// Get the identifier value of an instance or proxy. /// <p/> /// Intended only for loggin purposes!!! /// </summary> /// <param name="obj">The object from which to extract the identifier.</param> /// <param name="persister">The entity persister </param> /// <param name="entityMode">The entity mode </param> /// <returns> The extracted identifier. </returns> private static object GetIdentifier(object obj, IEntityPersister persister, EntityMode entityMode) { INHibernateProxy proxy = obj as INHibernateProxy; if (proxy != null) { ILazyInitializer li = proxy.HibernateLazyInitializer; return(li.Identifier); } else { return(persister.GetIdentifier(obj, entityMode)); } }
/// <summary> /// Get the identifier value of an instance or proxy. /// <p/> /// Intended only for loggin purposes!!! /// </summary> /// <param name="obj">The object from which to extract the identifier.</param> /// <param name="persister">The entity persister </param> /// <returns> The extracted identifier. </returns> private static object GetIdentifier(object obj, IEntityPersister persister) { if (obj.IsProxy()) { INHibernateProxy proxy = obj as INHibernateProxy; ILazyInitializer li = proxy.HibernateLazyInitializer; return(li.Identifier); } else { return(persister.GetIdentifier(obj)); } }
public static Object GetIdentifier(ISessionImplementor session, Object obj) { if (obj == null) { return(null); } if (obj is INHibernateProxy) { INHibernateProxy hibernateProxy = (INHibernateProxy)obj; return(hibernateProxy.HibernateLazyInitializer.Identifier); } return(session.GetEntityPersister(null, obj).GetIdentifier(obj, session.EntityMode)); }
public static object GetTargetFromProxy(ISessionImplementor session, INHibernateProxy proxy) { if (!proxy.HibernateLazyInitializer.IsUninitialized) { return(proxy.HibernateLazyInitializer.GetImplementation()); } var lazyInitializer = proxy.HibernateLazyInitializer; var proxySession = (ISession)lazyInitializer.Session; var tempSession = proxySession == null ? CreateChildSession((ISession)session) : CreateChildSession(proxySession); return(tempSession.Get(lazyInitializer.EntityName, lazyInitializer.Identifier)); }
/// <summary> /// Resolves the identifier to the actual object. /// </summary> protected object ResolveIdentifier(object id, ISessionImplementor session) { string entityName = GetAssociatedEntityName(); bool isProxyUnwrapEnabled = unwrapProxy && session.Factory .GetEntityPersister(entityName).IsInstrumented; object proxyOrEntity = session.InternalLoad(entityName, id, eager, IsNullable && !isProxyUnwrapEnabled); if (proxyOrEntity.IsProxy()) { INHibernateProxy proxy = (INHibernateProxy)proxyOrEntity; proxy.HibernateLazyInitializer.Unwrap = isProxyUnwrapEnabled; } return(proxyOrEntity); }
/// <summary> /// Resolves the identifier to the actual object. /// </summary> protected object ResolveIdentifier(object id, ISessionImplementor session) { bool isProxyUnwrapEnabled = unwrapProxy && session.Factory .GetEntityPersister(GetAssociatedEntityName()) .IsInstrumented(session.EntityMode); object proxyOrEntity = session.InternalLoad(GetAssociatedEntityName(), id, eager, IsNullable && !isProxyUnwrapEnabled); INHibernateProxy proxy = proxyOrEntity as INHibernateProxy; if (proxy != null) { proxy.HibernateLazyInitializer.Unwrap = isProxyUnwrapEnabled; } return(proxyOrEntity); }
/// <summary> /// Resolves the identifier to the actual object. /// </summary> protected async Task <object> ResolveIdentifierAsync(object id, ISessionImplementor session, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); string entityName = GetAssociatedEntityName(); bool isProxyUnwrapEnabled = unwrapProxy && session.Factory .GetEntityPersister(entityName).IsInstrumented; object proxyOrEntity = await(session.InternalLoadAsync(entityName, id, eager, IsNullable && !isProxyUnwrapEnabled, cancellationToken)).ConfigureAwait(false); if (proxyOrEntity.IsProxy()) { INHibernateProxy proxy = (INHibernateProxy)proxyOrEntity; proxy.HibernateLazyInitializer.Unwrap = isProxyUnwrapEnabled; } return(proxyOrEntity); }
public override Object MapToIdFromEntity(Object data) { if (data == null) { return(null); } if (data is INHibernateProxy) { INHibernateProxy hibernateProxy = (INHibernateProxy)data; return(hibernateProxy.HibernateLazyInitializer.Identifier); } else { PropertyInfo propInfo = data.GetType().GetProperty(propertyData.Name); return(propInfo.GetValue(data, null)); } }
public async Task ProxyRemainsUninitializedWhenReferencingIdPropertyAsync() { using (ISession session = base.OpenSession()) { ITest b = await(session.CreateQuery("from Test").UniqueResultAsync <Test>()); Assert.IsNotNull(b); INHibernateProxy proxy = b.Category as INHibernateProxy; Assert.That(proxy, Is.Not.Null); Assert.That(proxy.HibernateLazyInitializer.IsUninitialized, "Proxy should be uninitialized."); long cid = b.Category.Cid; Assert.That(proxy.HibernateLazyInitializer.IsUninitialized, "Proxy should still be uninitialized."); } }
public override void MapToMapFromEntity(IDictionary <String, Object> data, Object obj) { if (obj == null) { data.Add(propertyData.Name, null); } else { if (obj is INHibernateProxy) { INHibernateProxy hibernateProxy = (INHibernateProxy)obj; data.Add(propertyData.Name, hibernateProxy.HibernateLazyInitializer.Identifier); } else { PropertyInfo propInfo = obj.GetType().GetProperty(propertyData.BeanName); data.Add(propertyData.Name, propInfo.GetValue(obj, null)); } } }
public static Boolean IsDirtyProperty(this ISession session, Object entity, String propertyName) { ISessionImplementor sessionImpl = session.GetSessionImplementation(); IPersistenceContext persistenceContext = sessionImpl.PersistenceContext; EntityEntry oldEntry = persistenceContext.GetEntry(entity); String className = oldEntry.EntityName; IEntityPersister persister = sessionImpl.Factory.GetEntityPersister(className); if ((oldEntry == null) && (entity is INHibernateProxy)) { INHibernateProxy proxy = entity as INHibernateProxy; Object obj = sessionImpl.PersistenceContext.Unproxy(proxy); oldEntry = sessionImpl.PersistenceContext.GetEntry(obj); } Object[] oldState = oldEntry.LoadedState; Object[] currentState = persister.GetPropertyValues(entity, sessionImpl.EntityMode); Int32[] dirtyProps = persister.FindDirty(currentState, oldState, entity, sessionImpl); Int32 index = Array.IndexOf(persister.PropertyNames, propertyName); Boolean isDirty = (dirtyProps != null) ? (Array.IndexOf(dirtyProps, index) != -1) : false; return(isDirty); }
/// <summary> /// Get the true, underlying class of a proxied persistent class. This operation /// will NOT initialize the proxy and thus may return an incorrect result. /// </summary> /// <param name="entity">a persistable object or proxy</param> /// <returns>guessed class of the instance</returns> /// <remarks> /// This method is approximate match for Session.bestGuessEntityName in H3.2 /// </remarks> public static System.Type GuessClass(object entity) { INHibernateProxy proxy = entity as INHibernateProxy; if (proxy != null) { ILazyInitializer li = proxy.HibernateLazyInitializer; if (li.IsUninitialized) { return(li.PersistentClass); } else { return(li.GetImplementation().GetType()); } } else { return(entity.GetType()); } }
public override int GetHashCode(object x, ISessionFactoryImplementor factory) { IEntityPersister persister = factory.GetEntityPersister(associatedEntityName); if (!persister.CanExtractIdOutOfEntity) { return(base.GetHashCode(x)); } object id; if (x.IsProxy()) { INHibernateProxy proxy = x as INHibernateProxy; id = proxy.HibernateLazyInitializer.Identifier; } else { id = persister.GetIdentifier(x); } return(persister.IdentifierType.GetHashCode(id, factory)); }
public static bool IsDirtyEntity(this ISession session, object entity) { ISessionImplementor sessionImpl = session.GetSessionImplementation(); IPersistenceContext persistenceContext = sessionImpl.PersistenceContext; EntityEntry oldEntry = persistenceContext.GetEntry(entity); string className = oldEntry.EntityName; IEntityPersister persister = sessionImpl.Factory.GetEntityPersister(className); if ((oldEntry == null) && (entity is INHibernateProxy)) { INHibernateProxy proxy = entity as INHibernateProxy; object obj = sessionImpl.PersistenceContext.Unproxy(proxy); oldEntry = sessionImpl.PersistenceContext.GetEntry(obj); } object[] oldState = oldEntry.LoadedState; object[] currentState = persister.GetPropertyValues(entity, sessionImpl.EntityMode); int[] dirtyProps = oldState.Select((o, i) => (oldState[i] == currentState[i]) ? -1 : i).Where(x => x >= 0).ToArray(); return(dirtyProps != null); }
/// <summary> /// associate a proxy that was instantiated by another session with this session /// </summary> /// <param name="li"></param> /// <param name="proxy"></param> private void ReassociateProxy( LazyInitializer li, INHibernateProxy proxy ) { if( li.Session != this ) { IClassPersister persister = GetClassPersister( li.PersistentClass ); Key key = new Key( li.Identifier, persister ); if( !proxiesByKey.Contains( key ) ) { proxiesByKey[ key ] = proxy; // any earlier proxy takes precedence } NHibernateProxyHelper.GetLazyInitializer( proxy ).Session = this; } }
/// <summary> /// If the existing proxy is insufficiently "narrow" (derived), instantiate a new proxy /// and overwrite the registration of the old one. This breaks == and occurs only for /// "class" proxies rather than "interface" proxies. Also init the proxy to point to /// the given target implementation if necessary. /// </summary> /// <param name="proxy">The proxy instance to be narrowed. </param> /// <param name="persister">The persister for the proxied entity. </param> /// <param name="key">The internal cache key for the proxied entity. </param> /// <param name="obj">(optional) the actual proxied entity instance. </param> /// <returns> An appropriately narrowed instance. </returns> public object NarrowProxy(INHibernateProxy proxy, IEntityPersister persister, EntityKey key, object obj) { bool alreadyNarrow = persister.GetConcreteProxyClass(session.EntityMode).IsAssignableFrom(proxy.GetType()); if (!alreadyNarrow) { if (ProxyWarnLog.IsWarnEnabled) { ProxyWarnLog.Warn("Narrowing proxy to " + persister.GetConcreteProxyClass(session.EntityMode) + " - this operation breaks =="); } if (obj != null) { proxiesByKey.Remove(key); return obj; //return the proxied object } else { proxy = (INHibernateProxy)persister.CreateProxy(key.Identifier, session); proxiesByKey[key] = proxy; //overwrite old proxy return proxy; } } else { if (obj != null) { proxy.HibernateLazyInitializer.SetImplementation(obj); } return proxy; } }
/// <summary> /// Associate a proxy that was instantiated by another session with this session /// </summary> /// <param name="li">The proxy initializer. </param> /// <param name="proxy">The proxy to reassociate. </param> private void ReassociateProxy(ILazyInitializer li, INHibernateProxy proxy) { if (li.Session != Session) { IEntityPersister persister = session.Factory.GetEntityPersister(li.EntityName); EntityKey key = new EntityKey(li.Identifier, persister, session.EntityMode); // any earlier proxy takes precedence if (!proxiesByKey.ContainsKey(key)) { proxiesByKey[key] = proxy; } proxy.HibernateLazyInitializer.Session = Session; } }
/// <summary> Is the given proxy associated with this persistence context?</summary> public bool ContainsProxy(INHibernateProxy proxy) { return proxiesByKey.ContainsValue(proxy); }
/// <summary> Add a proxy to the session cache</summary> public void AddProxy(EntityKey key, INHibernateProxy proxy) { proxiesByKey[key] = proxy; }
private object InitializeOrGetAssociation(INHibernateProxy value, string fieldName) { if(value.HibernateLazyInitializer.IsUninitialized) { value.HibernateLazyInitializer.Initialize(); value.HibernateLazyInitializer.Unwrap = true; // means that future Load/Get from the session will get the implementation loadedUnwrapProxyFieldNames.Add(fieldName); } return value.HibernateLazyInitializer.GetImplementation(session); }
private void SetProxyReadOnly(INHibernateProxy proxy, bool readOnly) { if (proxy.HibernateLazyInitializer.Session != this.Session) { throw new AssertionFailure("Attempt to set a proxy to read-only that is associated with a different session"); } proxy.HibernateLazyInitializer.ReadOnly = readOnly; }