NHibernate SaveOrUpdate() improperly working with GeneratedBy.Assigned() - nhibernate

NHibernate's documentations specifically says
5.1.4.7. Assigned Identifiers
If you want the application to assign identifiers (as opposed to having NHibernate generate them), you may use the assigned generator. This special generator will use the identifier value already assigned to the object's identifier property. Be very careful when using this feature to assign keys with business meaning (almost always a terrible design decision).
Due to its inherent nature, entities that use this generator cannot be saved via the ISession's SaveOrUpdate() method. Instead you have to explicitly specify to NHibernate if the object should be saved or updated by calling either the Save() or Update() method of the ISession.
But I am using assigned identifiers and session.SaveOrUpdate() and I'm not getting an error/warning of any sort.
What am I missing? Did they change how SaveOrUpdate behaves and now it can be used with assigned identifiers?
I am also using Fluent NHibernate's auto mapping.
Here's the code:
public class MyIDConvention : IIdConvention
{
public void Apply(IIdentityInstance instance)
{
instance.GeneratedBy.Assigned();
}
}
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure().Database(SQLiteConfiguration.Standard.UsingFile("testDB.db"))
.Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Product>(cfg).Conventions.Add<MyIDConvention>()
.BuildSessionFactory();
}
I'm expecting an error when I do:
Product myProduct = new Product(presetID);
session.SaveOrUpdate(myProduct);
transaction.Commit();
but nothing happens.
If I had left out the myIDConvention, then I get the error:
NHibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect).
Can anyone explain to me what is going on?

When using assigned ids NHibernate can determine if the entity is persistent by comparing the id to the unsaved value setting. My understanding is that the unsaved value setting allows SaveOrUpdate to be used and the documentation you referenced is outdated/misleading.
For example, if your id is int the default unsaved-value is 0.
5.1.4
unsaved-value (optional - defaults to a "sensible" value): An
identifier property value that indicates that an instance is newly
instantiated (unsaved), distinguishing it from transient instances
that were saved or loaded in a previous session.

Related

How can I make a where clause on a reference in fluent-nhibernate mapping

There exists such a method on HasMany and HasManyToMany but for some reason there isn't such a mechanism on References.
We have an object that references an other object that can be updated and saved as new versions but from our child object we doesn't really care we only want to load the latest version of the related object. The mapping cannot use the primary key for the related object since this will change for each version of the object so instead we want to map the related object to an property that doesn't change between versions and then make a where-clause to only selected the matching element with the highest version.
So our mapping is like the following
References(p => p.RelatedObjectIdentifier).PropertyRef("MatchingPropIdentifier").Not.Nullable;
We would like to do something like this
References(p => p.RelatedObjectIdentifier).PropertyRef("MatchingPropIdentifier").Where(p => p.IsLatest).Not.Nullable;
Of course we would update the property IsLatest (bool property) for each saving of the related object.
So since the Where(p => p.IsLatest) doesn't exist on a References for a classmap/subclassmap how can we make this happen in any other way?
You can only use the Where() restriction, which:
Defines a SQL 'where' clause used when retrieving objects of this type.
on the class map of the referenced type.
Example:
public class RelatedObjectMap : ClassMap<RelatedObject>
{
public RelatedObjectMap()
{
Table("RelatedObjectTable");
//Id() etc.
Where("MatchingPropIdentifier IS NOT NULL)");
}
}

Setting an entity's ID manually

I'm facing a little issue that I cannot understand here.
Using this chunk of code:
IEntity myEntity = controller.entityFactory.createEntityInstance(MyEntity.class)
myEntity.straightSetProperty(IEntity.ID, "anId")
myEntity.setReferenceProperty(someReference)
I get an "UOW bad usage" error
BAD SESSION USAGE You are modifying an entity ()[MyEntity] that has not been previously merged in the session.
You should 1st merge your entities in the session by using the backendController.merge(...) method.
The property being modified is [referenceProperty].
But when switching the lines it's okay
IEntity myEntity = controller.entityFactory.createEntityInstance(MyEntity.class)
myEntity.setReferenceProperty(someReference)
myEntity.straightSetProperty(IEntity.ID, "anId")
Any idea why i'm facing this issue ?
Jspresso computes the hashcode of an entity based on its id. this hashcode is indirectly used by Jspresso internally to perform some controls and other operations by using it in Hash[Map|Set].
That's why it's mandatory that :
The id is assigned as soon as the entity instance is created and before any setter or operation is performed on the entity.
The id does not change during the lifetime of the entity.
When you call :
IEntity myEntity = entityFactory.createEntityInstance(MyEntity.class)
a generated id is assigned to the entity.
In scenario 1, you first change the id (which breaks the hashcode), and call a setter. Jspresso thinks this entity has not been correctly registered because it cannot retrieve its id from the internal, hashcode based, storage.
In scenario 2, same violation but you call the setter before changing the id. But I suppose that if you call another setter afterwards, it will fail the same way.
The solution is to use the other signature of the entityFactory create method that allows to pass an id as parameter, e.g.
IEntity myEntity = entityFactory.createEntityInstance(MyEntity.class, "anId")
myEntity.setReferenceProperty(someReference)
which will immediately assign your id to the entity and perform all necessary operations afterwards.

Expected behaviour of a Repository

I'm writing an ORM and am unsure of the expected behaviour of the Repository, or more precisely, the frontier between the Repository and the Unit Of Work.
From my understanding, a Repository might look like this:
interface IPersonRepository
{
public function find(Criteria criteria);
public function add(Person person);
public function delete(Person person);
}
According to Fowler (PoEAA, page 322):
A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. [...] Objects can be added to and removed from the Repository, as they can from a simple collection of objects.
This would imply that the following test should work (assuming that we already have a Person persisted, whose last name is Fowler):
collection = repository.find(lastnameEqualsFowlerCriteria);
person = collection[0];
assertEquals(person.lastname, "Fowler");
person.lastname = "Evans";
newCollection = repository.find(lastnameEqualsFowlerCriteria);
assertFalse(newCollection.contains(person));
That means that when mapping to a database, even if no explicit save() method has been called somewhere, the Person model must have been automatically persisted by the Repository, so that the next query returned the correct collection, not containing the original Person.
But, isn't that the role of the Unit Of Work, to decide which model to persist to the database, and when?
In the above implementation, the Repository has to decide to persist the Person previously retrieved when receiving another find() call, so that the result is consistent with the modification. But if no other find() call were issued, the model would not have been persisted implicitly at all.
In the context of a Unit Of Work, it is not really a problem, because we can start a transaction at the beginning, and rollback any insert to the db anyway if needed.
But when used alone, can't this Repository lead to unexpected, unpredictable behaviour?
A Repository mediates between the
domain and data mapping layers, acting
like an in-memory domain object
collection. [...] Objects can be added
to and removed from the Repository, as
they can from a simple collection of
objects.
This does not mean you do not need a save method. You still need to explicitly commit your changes to storage.
See The Unit Of Work Pattern And Persistence Ignorance
public interface IUnitOfWork {
void MarkDirty(object entity);
void MarkNew(object entity);
void MarkDeleted(object entity);
void Commit();
void Rollback();
}
In a way, you can think of the Unit of Work as a place to dump all transaction-handling code. The responsibilities of the Unit of Work are to:
Manage transactions.
Order the database inserts, deletes, and updates.
Prevent duplicate updates. Inside a single usage of a Unit of Work object, different parts of the code may mark the same Invoice object as changed, but the Unit of Work class will only issue a single UPDATE command to the databas
I think what you;re asking about is following: http://martinfowler.com/eaaCatalog/identityMap.html
Repository should keep fetched objects in memory and all subsequent calls for that entity should not be retrieved from persistence storage, hence your example should work fine.

How do you audit changed collections in NHibernate?

I've been using the IPreUpdateEventListener for auditing entities, in particular using the FindDirty method to find the changed properties:
public bool OnPreUpdate(PreUpdateEvent updateEvent)
{
int[] dirtyFieldIndices = updateEvent.Persister.FindDirty(updateEvent.State, updateEvent.OldState, updateEvent.Entity, updateEvent.Session);
// Get changed property names and audit...
}
This works fine for simple properties. However, my entity has a collection property of other entities. One of these entities has changed, and the change gets persisted, but FindDirty does not give me the index of that collection property. Is there any way of getting hold of the changed property in order to audit this change?
I have decided to have a method on my domain objects that receives the OldState collection, and applies its own processing on it, checking each object to see if it has changed.

Ensuring inserts after a call to a custom NHibernate IIdentifierGenerator

The setup
Some of the "old old old" tables of our database use an exotic primary key generation scheme [1] and I'm trying to overlay this part of the database with NHibernate. This generation scheme is mostly hidden away in a stored procedure called, say, 'ShootMeInTheFace.GetNextSeededId'.
I have written an IIdentifierGenerator that calls this stored proc:
public class LegacyIdentityGenerator : IIdentifierGenerator, IConfigurable
{
// ... snip ...
public object Generate(ISessionImplementor session, object obj)
{
var connection = session.Connection;
using (var command = connection.CreateCommand())
{
SqlParameter param;
session.ConnectionManager.Transaction.Enlist(command);
command.CommandText = "ShootMeInTheFace.GetNextSeededId";
command.CommandType = CommandType.StoredProcedure;
param = command.CreateParameter() as SqlParameter;
param.Direction = ParameterDirection.Input;
param.ParameterName = "#sTableName";
param.SqlDbType = SqlDbType.VarChar;
param.Value = this.table;
command.Parameters.Add(param);
// ... snip ...
command.ExecuteNonQuery();
// ... snip ...
return ((IDataParameter)command
.Parameters["#sTrimmedNewId"]).Value as string);
}
}
The problem
I can map this in the XML mapping files and it works great, BUT....
It doesn't work when NHibernate tries to batch inserts, such as in a cascade, or when the session is not Flush()ed after every call to Save() on a transient entity that depends on this generator.
That's because NHibernate seems to be doing something like
for (each thing that I need to save)
{
[generate its id]
[add it to the batch]
}
[execute the sql in one big batch]
This doesn't work because, since the generator is asking the database every time, NHibernate just ends up getting the same ID generated multiple times, since it hasn't actually saved anything yet.
The other NHibernate generators like IncrementGenerator seem to get around this by asking the database for the seed value once and then incrementing the value in memory during subsequent calls in the same session. I would rather not do this in my implementation if I have to, since all of the code that I need is sitting in the database already, just waiting for me to call it correctly.
Is there a way to make NHibernate actually issue the INSERT after each call to generating an ID for entities of a certain type? Fiddling with the batch size settings don't seem to help.
Do you have any suggestions/other workarounds besides re-implementing the generation code in memory or bolting on some triggers to the legacy database? I guess I could always treat these as "assigned" generators and try to hide that fact somehow within the guts of the domain model....
Thanks for any advice.
The update: 2 months later
It was suggested in the answers below that I use an IPreInsertEventListener to implement this functionality. While this sounds reasonable, there were a few problems with this.
The first problem was that setting the id of an entity to the AssignedGenerator and then not actually assigning anything in code (since I was expecting my new IPreInsertEventListener implementation to do the work) resulted in an exception being thrown by the AssignedGenerator, since its Generate() method essentially does nothing but check to make sure that the id is not null, throwing an exception otherwise. This is worked around easily enough by creating my own IIdentifierGenerator that is like AssignedGenerator without the exception.
The second problem was that returning null from my new IIdentifierGenerator (the one I wrote to overcome the problems with the AssignedGenerator resulted in the innards of NHibernate throwing an exception, complaining that a null id was generated. Okay, fine, I changed my IIdentifierGenerator to return a sentinel string value, say, "NOT-REALLY-THE-REAL-ID", knowing that my IPreInsertEventListener would replace it with the correct value.
The third problem, and the ultimate deal-breaker, was that IPreInsertEventListener runs so late in the process that you need to update both the actual entity object as well as an array of state values that NHibernate uses. Typically this is not a problem and you can just follow Ayende's example. But there are three issues with the id field relating to the IPreInsertEventListeners:
The property is not in the #event.State array but instead in its own Id property.
The Id property does not have a public set accessor.
Updating only the entity but not the Id property results in the "NOT-REALLY-THE-REAL-ID" sentinel value being passed through to the database since the IPreInsertEventListener was unable to insert in the right places.
So my choice at this point was to use reflection to get at that NHibernate property, or to really sit down and say "look, the tool just wasn't meant to be used this way."
So I went back to my original IIdentifierGenreator and made it work for lazy flushes: it got the high value from the database on the first call, and then I re-implemented that ID generation function in C# for subsequent calls, modeling this after the Increment generator:
private string lastGenerated;
public object Generate(ISessionImplementor session, object obj)
{
string identity;
if (this.lastGenerated == null)
{
identity = GetTheValueFromTheDatabase();
}
else
{
identity = GenerateTheNextValueInCode();
}
this.lastGenerated = identity;
return identity;
}
This seems to work fine for a while, but like the increment generator, we might as well call it the TimeBombGenerator. If there are multiple worker processes executing this code in non-serializable transactions, or if there are multiple entities mapped to the same database table (it's an old database, it happened), then we will get multiple instances of this generator with the same lastGenerated seed value, resulting in duplicate identities.
##$##$#.
My solution at this point was to make the generator cache a dictionary of WeakReferences to ISessions and their lastGenerated values. This way, the lastGenerated is effectively local to the lifetime of a particular ISession, not the lifetime of the IIdentifierGenerator, and because I'm holding WeakReferences and culling them out at the beginning of each Generate() call, this won't explode in memory consumption. And since each ISession is going to hit the database table on its first call, we'll get the necessary row locks (assuming we're in a transaction) we need to prevent duplicate identities from happening (and if they do, such as from a phantom row, only the ISession needs to be thrown away, not the entire process).
It is ugly, but more feasible than changing the primary key scheme of a 10-year-old database. FWIW.
[1] If you care to know about the ID generation, you take a substring(len - 2) of all of the values currently in the PK column, cast them to integers and find the max, add one to that number, add all of that number's digits, and append the sum of those digits as a checksum. (If the database has one row containing "1000001", then we would get max 10000, +1 equals 10001, checksum is 02, resulting new PK is "1000102". Don't ask me why.
A potential workaround is to generate and assign the ID in an event listener rather than using an IIdentifierGenerator implementation. The listener should implement IPreInsertEventListener and assign the ID in OnPreInsert.
Why dont you just make private string lastGenerated; static?