Skip to content

Commit

Permalink
Centralize creation of EntityKey and CacheKey into AbstractSessionImp…
Browse files Browse the repository at this point in the history
…l. This is in preparation for multi tenancy (NH-3087). Based on work by Paul White in pull request #91.
  • Loading branch information
oskarb committed May 26, 2012
1 parent 8ed010d commit ce60683
Show file tree
Hide file tree
Showing 39 changed files with 109 additions and 79 deletions.
2 changes: 1 addition & 1 deletion src/NHibernate.DomainModel/CustomPersister.cs
Expand Up @@ -317,7 +317,7 @@ public object Load(object id, object optionalObject, LockMode lockMode, ISession
if (obj != null)
{
clone = (Custom)obj.Clone();
TwoPhaseLoad.AddUninitializedEntity(new EntityKey(id, this, session.EntityMode), clone, this, LockMode.None, false,
TwoPhaseLoad.AddUninitializedEntity(session.GenerateEntityKey(id, this), clone, this, LockMode.None, false,
session);
TwoPhaseLoad.PostHydrate(this, id, new String[] {obj.Name}, null, clone, LockMode.None, false, session);
TwoPhaseLoad.InitializeEntity(clone, false, session, new PreLoadEvent((IEventSource) session),
Expand Down
6 changes: 3 additions & 3 deletions src/NHibernate/Action/CollectionAction.cs
Expand Up @@ -96,7 +96,7 @@ public virtual void BeforeExecutions()
// second-level cache invalidation only)
if (persister.HasCache)
{
CacheKey ck = new CacheKey(key, persister.KeyType, persister.Role, session.EntityMode, session.Factory);
CacheKey ck = session.GenerateCacheKey(key, persister.KeyType, persister.Role);
softLock = persister.Cache.Lock(ck, null);
}
}
Expand All @@ -120,7 +120,7 @@ public virtual AfterTransactionCompletionProcessDelegate AfterTransactionComplet
{
if (persister.HasCache)
{
CacheKey ck = new CacheKey(key, persister.KeyType, persister.Role, Session.EntityMode, Session.Factory);
CacheKey ck = Session.GenerateCacheKey(key, persister.KeyType, persister.Role);
persister.Cache.Release(ck, softLock);
}
});
Expand All @@ -138,7 +138,7 @@ protected internal void Evict()
{
if (persister.HasCache)
{
CacheKey ck = new CacheKey(key, persister.KeyType, persister.Role, session.EntityMode, session.Factory);
CacheKey ck = session.GenerateCacheKey(key, persister.KeyType, persister.Role);
persister.Cache.Evict(ck);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/NHibernate/Action/CollectionUpdateAction.cs
Expand Up @@ -130,7 +130,7 @@ public override AfterTransactionCompletionProcessDelegate AfterTransactionComple
// NH Different behavior: to support unlocking collections from the cache.(r3260)
if (Persister.HasCache)
{
CacheKey ck = new CacheKey(Key, Persister.KeyType, Persister.Role, Session.EntityMode, Session.Factory);
CacheKey ck = Session.GenerateCacheKey(Key, Persister.KeyType, Persister.Role);
if (success)
{
Expand Down
6 changes: 3 additions & 3 deletions src/NHibernate/Action/EntityDeleteAction.cs
Expand Up @@ -57,7 +57,7 @@ public override void Execute()
CacheKey ck;
if (persister.HasCache)
{
ck = new CacheKey(id, persister.IdentifierType, persister.RootEntityName, session.EntityMode, session.Factory);
ck = session.GenerateCacheKey(id, persister.IdentifierType, persister.RootEntityName);
sLock = persister.Cache.Lock(ck, version);
}
else
Expand All @@ -83,7 +83,7 @@ public override void Execute()
}
entry.PostDelete();

EntityKey key = new EntityKey(entry.Id, entry.Persister, session.EntityMode);
EntityKey key = session.GenerateEntityKey(entry.Id, entry.Persister);
persistenceContext.RemoveEntity(key);
persistenceContext.RemoveProxy(key);

Expand Down Expand Up @@ -131,7 +131,7 @@ protected override void AfterTransactionCompletionProcessImpl(bool success)
{
if (Persister.HasCache)
{
CacheKey ck = new CacheKey(Id, Persister.IdentifierType, Persister.RootEntityName, Session.EntityMode, Session.Factory);
CacheKey ck = Session.GenerateCacheKey(Id, Persister.IdentifierType, Persister.RootEntityName);
Persister.Cache.Release(ck, sLock);
}
if (success)
Expand Down
2 changes: 1 addition & 1 deletion src/NHibernate/Action/EntityIdentityInsertAction.cs
Expand Up @@ -41,7 +41,7 @@ private EntityKey GenerateDelayedEntityKey()
if (!isDelayed)
throw new HibernateException("Cannot request delayed entity-key for non-delayed post-insert-id generation");

return new EntityKey(new DelayedPostInsertIdentifier(), Persister, Session.EntityMode);
return Session.GenerateEntityKey(new DelayedPostInsertIdentifier(), Persister);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/NHibernate/Action/EntityInsertAction.cs
Expand Up @@ -84,7 +84,7 @@ public override void Execute()
CacheEntry ce = new CacheEntry(state, persister, persister.HasUninitializedLazyProperties(instance, session.EntityMode), version, session, instance);
cacheEntry = persister.CacheEntryStructure.Structure(ce);

CacheKey ck = new CacheKey(id, persister.IdentifierType, persister.RootEntityName, Session.EntityMode, Session.Factory);
CacheKey ck = Session.GenerateCacheKey(id, persister.IdentifierType, persister.RootEntityName);
bool put = persister.Cache.Insert(ck, cacheEntry, version);

if (put && factory.Statistics.IsStatisticsEnabled)
Expand All @@ -108,7 +108,7 @@ protected override void AfterTransactionCompletionProcessImpl(bool success)
IEntityPersister persister = Persister;
if (success && IsCachePutEnabled(persister))
{
CacheKey ck = new CacheKey(Id, persister.IdentifierType, persister.RootEntityName, Session.EntityMode, Session.Factory);
CacheKey ck = Session.GenerateCacheKey(Id, persister.IdentifierType, persister.RootEntityName);
bool put = persister.Cache.AfterInsert(ck, cacheEntry, version);

if (put && Session.Factory.Statistics.IsStatisticsEnabled)
Expand Down
4 changes: 2 additions & 2 deletions src/NHibernate/Action/EntityUpdateAction.cs
Expand Up @@ -70,7 +70,7 @@ public override void Execute()
CacheKey ck = null;
if (persister.HasCache)
{
ck = new CacheKey(id, persister.IdentifierType, persister.RootEntityName, session.EntityMode, factory);
ck = session.GenerateCacheKey(id, persister.IdentifierType, persister.RootEntityName);
slock = persister.Cache.Lock(ck, previousVersion);
}

Expand Down Expand Up @@ -140,7 +140,7 @@ protected override void AfterTransactionCompletionProcessImpl(bool success)
IEntityPersister persister = Persister;
if (persister.HasCache)
{
CacheKey ck = new CacheKey(Id, persister.IdentifierType, persister.RootEntityName, Session.EntityMode, Session.Factory);
CacheKey ck = Session.GenerateCacheKey(Id, persister.IdentifierType, persister.RootEntityName);

if (success && cacheEntry != null)
{
Expand Down
24 changes: 10 additions & 14 deletions src/NHibernate/Engine/BatchFetchQueue.cs
Expand Up @@ -136,7 +136,7 @@ public void RemoveBatchLoadableEntityKey(EntityKey key)
/// <param name="batchSize">the maximum number of keys to return</param>
/// <param name="entityMode">The entity mode.</param>
/// <returns>an array of collection keys, of length batchSize (padded with nulls)</returns>
public object[] GetCollectionBatch(ICollectionPersister collectionPersister, object id, int batchSize, EntityMode entityMode)
public object[] GetCollectionBatch(ICollectionPersister collectionPersister, object id, int batchSize)
{
object[] keys = new object[batchSize];
keys[0] = id;
Expand All @@ -160,14 +160,14 @@ public object[] GetCollectionBatch(ICollectionPersister collectionPersister, obj

//if ( end == -1 && count > batchSize*10 ) return keys; //try out ten batches, max

bool isEqual = collectionPersister.KeyType.IsEqual(id, ce.LoadedKey, entityMode, collectionPersister.Factory);
bool isEqual = collectionPersister.KeyType.IsEqual(id, ce.LoadedKey, context.Session.EntityMode, collectionPersister.Factory);

if (isEqual)
{
end = i;
//checkForEnd = false;
}
else if (!IsCached(ce.LoadedKey, collectionPersister, entityMode))
else if (!IsCached(ce.LoadedKey, collectionPersister))
{
keys[i++] = ce.LoadedKey;
//count++;
Expand All @@ -194,9 +194,8 @@ public object[] GetCollectionBatch(ICollectionPersister collectionPersister, obj
/// <param name="persister">The persister for the entities being loaded.</param>
/// <param name="id">The identifier of the entity currently demanding load.</param>
/// <param name="batchSize">The maximum number of keys to return</param>
/// <param name="entityMode">The entity mode.</param>
/// <returns>an array of identifiers, of length batchSize (possibly padded with nulls)</returns>
public object[] GetEntityBatch(IEntityPersister persister,object id,int batchSize, EntityMode entityMode)
public object[] GetEntityBatch(IEntityPersister persister,object id,int batchSize)
{
object[] ids = new object[batchSize];
ids[0] = id; //first element of array is reserved for the actual instance we are loading!
Expand All @@ -214,13 +213,13 @@ public object[] GetEntityBatch(IEntityPersister persister,object id,int batchSiz
//the first id found after the given id
return ids;
}
if (persister.IdentifierType.IsEqual(id, key.Identifier, entityMode))
if (persister.IdentifierType.IsEqual(id, key.Identifier, context.Session.EntityMode))
{
end = i;
}
else
{
if (!IsCached(key, persister, entityMode))
if (!IsCached(key, persister))
{
ids[i++] = key.Identifier;
}
Expand All @@ -236,24 +235,21 @@ public object[] GetEntityBatch(IEntityPersister persister,object id,int batchSiz
return ids; //we ran out of ids to try
}

private bool IsCached(EntityKey entityKey, IEntityPersister persister, EntityMode entityMode)
private bool IsCached(EntityKey entityKey, IEntityPersister persister)
{
if (persister.HasCache)
{
CacheKey key =
new CacheKey(entityKey.Identifier, persister.IdentifierType, entityKey.EntityName, entityMode,
context.Session.Factory);
CacheKey key = context.Session.GenerateCacheKey(entityKey.Identifier, persister.IdentifierType, entityKey.EntityName);
return persister.Cache.Cache.Get(key) != null;
}
return false;
}

private bool IsCached(object collectionKey, ICollectionPersister persister, EntityMode entityMode)
private bool IsCached(object collectionKey, ICollectionPersister persister)
{
if (persister.HasCache)
{
CacheKey cacheKey =
new CacheKey(collectionKey, persister.KeyType, persister.Role, entityMode, context.Session.Factory);
CacheKey cacheKey = context.Session.GenerateCacheKey(collectionKey, persister.KeyType, persister.Role);
return persister.Cache.Cache.Get(cacheKey) != null;
}
return false;
Expand Down
2 changes: 1 addition & 1 deletion src/NHibernate/Engine/Collections.cs
Expand Up @@ -60,7 +60,7 @@ private static void ProcessDereferencedCollection(IPersistentCollection coll, IS
// throw new AssertionFailure("Unable to determine collection owner identifier for orphan-delete processing");
// }
//}
EntityKey key = new EntityKey(ownerId, loadedPersister.OwnerEntityPersister, session.EntityMode);
EntityKey key = session.GenerateEntityKey(ownerId, loadedPersister.OwnerEntityPersister);
object owner = persistenceContext.GetEntity(key);
if (owner == null)
{
Expand Down
2 changes: 1 addition & 1 deletion src/NHibernate/Engine/EntityEntry.cs
Expand Up @@ -260,7 +260,7 @@ public void ForceLocked(object entity, object nextVersion)

public bool IsNullifiable(bool earlyInsert, ISessionImplementor session)
{
return Status == Status.Saving || (earlyInsert ? !ExistsInDatabase : session.PersistenceContext.NullifiableEntityKeys.Contains(new EntityKey(Id, Persister, entityMode)));
return Status == Status.Saving || (earlyInsert ? !ExistsInDatabase : session.PersistenceContext.NullifiableEntityKeys.Contains(session.GenerateEntityKey(Id, Persister)));
}

public bool RequiresDirtyCheck(object entity)
Expand Down
5 changes: 5 additions & 0 deletions src/NHibernate/Engine/ISessionImplementor.cs
Expand Up @@ -3,6 +3,7 @@
using System.Collections.Generic;
using System.Data;
using NHibernate.AdoNet;
using NHibernate.Cache;
using NHibernate.Collection;
using NHibernate.Engine.Query.Sql;
using NHibernate.Event;
Expand Down Expand Up @@ -303,5 +304,9 @@ public interface ISessionImplementor
ITransactionContext TransactionContext { get; set; }

void CloseSessionFromDistributedTransaction();

EntityKey GenerateEntityKey(object id, IEntityPersister persister);

CacheKey GenerateCacheKey(object id, IType type, string entityOrRoleName);
}
}
2 changes: 1 addition & 1 deletion src/NHibernate/Engine/Loading/CollectionLoadContext.cs
Expand Up @@ -323,7 +323,7 @@ private void AddCollectionToCache(LoadingCollectionEntry lce, ICollectionPersist
}

CollectionCacheEntry entry = new CollectionCacheEntry(lce.Collection, persister);
CacheKey cacheKey = new CacheKey(lce.Key, persister.KeyType, persister.Role, session.EntityMode, factory);
CacheKey cacheKey = session.GenerateCacheKey(lce.Key, persister.KeyType, persister.Role);
bool put = persister.Cache.Put(cacheKey, persister.CacheEntryStructure.Structure(entry),
session.Timestamp, version, versionComparator,
factory.Settings.IsMinimalPutsEnabled && session.CacheMode != CacheMode.Refresh);
Expand Down
10 changes: 5 additions & 5 deletions src/NHibernate/Engine/StatefulPersistenceContext.cs
Expand Up @@ -330,7 +330,7 @@ public void AfterTransactionCompletion()
/// </summary>
public object[] GetDatabaseSnapshot(object id, IEntityPersister persister)
{
EntityKey key = new EntityKey(id, persister, session.EntityMode);
EntityKey key = session.GenerateEntityKey(id, persister);
object cached;
if (entitySnapshotsByKey.TryGetValue(key, out cached))
{
Expand Down Expand Up @@ -614,7 +614,7 @@ 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);
EntityKey key = session.GenerateEntityKey(li.Identifier, persister);
// any earlier proxy takes precedence
if (!proxiesByKey.ContainsKey(key))
{
Expand Down Expand Up @@ -777,13 +777,13 @@ public object ProxyFor(object impl)
{
EntityEntry e = GetEntry(impl);
IEntityPersister p = e.Persister;
return ProxyFor(p, new EntityKey(e.Id, p, session.EntityMode), impl);
return ProxyFor(p, session.GenerateEntityKey(e.Id, p), impl);
}

/// <summary> Get the entity that owns this persistent collection</summary>
public object GetCollectionOwner(object key, ICollectionPersister collectionPersister)
{
return GetEntity(new EntityKey(key, collectionPersister.OwnerEntityPersister, session.EntityMode));
return GetEntity(session.GenerateEntityKey(key, collectionPersister.OwnerEntityPersister));
}

/// <summary> Get the entity that owned this persistent collection when it was loaded </summary>
Expand Down Expand Up @@ -1351,7 +1351,7 @@ public void ReplaceDelayedEntityIdentityInsertKeys(EntityKey oldKey, object gene
var oldEntry = (EntityEntry) tempObject2;
parentsByChild.Clear();

var newKey = new EntityKey(generatedId, oldEntry.Persister, Session.EntityMode);
var newKey = Session.GenerateEntityKey(generatedId, oldEntry.Persister);
AddEntity(newKey, entity);
AddEntry(entity, oldEntry.Status, oldEntry.LoadedState, oldEntry.RowId, generatedId, oldEntry.Version,
oldEntry.LockMode, oldEntry.ExistsInDatabase, oldEntry.Persister, oldEntry.IsBeingReplicated,
Expand Down
2 changes: 1 addition & 1 deletion src/NHibernate/Engine/TwoPhaseLoad.cs
Expand Up @@ -106,7 +106,7 @@ public static void InitializeEntity(object entity, bool readOnly, ISessionImplem
object version = Versioning.GetVersion(hydratedState, persister);
CacheEntry entry =
new CacheEntry(hydratedState, persister, entityEntry.LoadedWithLazyPropertiesUnfetched, version, session, entity);
CacheKey cacheKey = new CacheKey(id, persister.IdentifierType, persister.RootEntityName, session.EntityMode, session.Factory);
CacheKey cacheKey = session.GenerateCacheKey(id, persister.IdentifierType, persister.RootEntityName);
bool put =
persister.Cache.Put(cacheKey, persister.CacheEntryStructure.Structure(entry), session.Timestamp, version,
persister.IsVersioned ? persister.VersionType.Comparator : null,
Expand Down
Expand Up @@ -47,7 +47,7 @@ protected virtual void UpgradeLock(object entity, EntityEntry entry, LockMode re
CacheKey ck;
if (persister.HasCache)
{
ck = new CacheKey(entry.Id, persister.IdentifierType, persister.RootEntityName, source.EntityMode, source.Factory);
ck = source.GenerateCacheKey(entry.Id, persister.IdentifierType, persister.RootEntityName);
slock = persister.Cache.Lock(ck, entry.Version);
}
else
Expand Down
Expand Up @@ -33,7 +33,7 @@ protected EntityEntry Reassociate(AbstractEvent @event, object entity, object id
}

IEventSource source = @event.Session;
EntityKey key = new EntityKey(id, persister, source.EntityMode);
EntityKey key = source.GenerateEntityKey(id, persister);

source.PersistenceContext.CheckUniqueness(key, entity);

Expand Down
4 changes: 2 additions & 2 deletions src/NHibernate/Event/Default/AbstractSaveEventListener.cs
Expand Up @@ -160,7 +160,7 @@ protected virtual object PerformSave(object entity, object id, IEntityPersister
EntityKey key;
if (!useIdentityColumn)
{
key = new EntityKey(id, persister, source.EntityMode);
key = source.GenerateEntityKey(id, persister);
object old = source.PersistenceContext.GetEntity(key);
if (old != null)
{
Expand Down Expand Up @@ -260,7 +260,7 @@ protected virtual object PerformSaveOrReplicate(object entity, EntityKey key, IE
id = insert.GeneratedId;
//now done in EntityIdentityInsertAction
//persister.setIdentifier( entity, id, source.getEntityMode() );
key = new EntityKey(id, persister, source.EntityMode);
key = source.GenerateEntityKey(id, persister);
source.PersistenceContext.CheckUniqueness(key, entity);
//source.getBatcher().executeBatch(); //found another way to ensure that all batched joined inserts have been executed
}
Expand Down
4 changes: 2 additions & 2 deletions src/NHibernate/Event/Default/DefaultDeleteEventListener.cs
Expand Up @@ -64,7 +64,7 @@ public virtual void OnDelete(DeleteEvent @event, ISet<object> transientEntities)
throw new TransientObjectException("the detached instance passed to delete() had a null identifier");
}

EntityKey key = new EntityKey(id, persister, source.EntityMode);
EntityKey key = source.GenerateEntityKey(id, persister);

persistenceContext.CheckUniqueness(key, entity);

Expand Down Expand Up @@ -196,7 +196,7 @@ protected virtual void DeleteEntity(IEventSource session, object entity, EntityE

// before any callbacks, etc, so subdeletions see that this deletion happened first
persistenceContext.SetEntryStatus(entityEntry, Status.Deleted);
EntityKey key = new EntityKey(entityEntry.Id, persister, session.EntityMode);
EntityKey key = session.GenerateEntityKey(entityEntry.Id, persister);

CascadeBeforeDelete(session, persister, entity, entityEntry, transientEntities);

Expand Down
2 changes: 1 addition & 1 deletion src/NHibernate/Event/Default/DefaultEvictEventListener.cs
Expand Up @@ -33,7 +33,7 @@ public virtual void OnEvict(EvictEvent @event)
{
throw new ArgumentException("null identifier");
}
EntityKey key = new EntityKey(id, persister, source.EntityMode);
EntityKey key = source.GenerateEntityKey(id, persister);
persistenceContext.RemoveProxy(key);
if (!li.IsUninitialized)
{
Expand Down
Expand Up @@ -522,7 +522,7 @@ private object[] GetDatabaseSnapshot(ISessionImplementor session, IEntityPersist
else
{
//TODO: optimize away this lookup for entities w/o unsaved-value="undefined"
EntityKey entityKey = new EntityKey(id, persister, session.EntityMode);
EntityKey entityKey = session.GenerateEntityKey(id, persister);
return session.PersistenceContext.GetCachedDatabaseSnapshot(entityKey);
}
}
Expand Down
Expand Up @@ -80,7 +80,7 @@ private bool InitializeCollectionFromCache(object id, ICollectionPersister persi
{
ISessionFactoryImplementor factory = source.Factory;

CacheKey ck = new CacheKey(id, persister.KeyType, persister.Role, source.EntityMode, factory);
CacheKey ck = source.GenerateCacheKey(id, persister.KeyType, persister.Role);
object ce = persister.Cache.Get(ck, source.Timestamp);

if (factory.Statistics.IsStatisticsEnabled)
Expand Down

0 comments on commit ce60683

Please sign in to comment.