In NH is a configuration setting 'use_identifier_rollback' which is sets the id of an entity back to its default value.
This settings works with every cascade options except 'delete-orphan'. (And I know why!)
Take a look at C# Identifier Rollback
Take a look at Java Identifier Rollback
// Works with 'use_identifier_rollback' and 'cascade-option=all'
// but not with 'cascade-option=all-delete-orphan'
Sample sample = new Sample("sample");
sample.Add(new Subsample("subsample");
int sampleId;
using(var session = sessionFactoy.OpenSession())
{
using(var tx = session.BeginTransaction())
{
session.Save(sample);
sampleId = sample.Id;
Assert.That(sampleId, Is.GreaterThan(0));
Assert.False(sample.IsTransient)
} // Rollback
}
Assert.That(sample.Id, Is.EqualTo(0));
Assert.True(sample.IsTransient)
Is it bad practice to revert the id when rollbacking the save? In the java code is not comment out and works.
UPDATE: What behavior do you usually expect when you delete an entity?
// Works with 'use_identifier_rollback' and 'cascade-option=all'
// but not with 'cascade-option=all-delete-orphan'
int sampleId; // sampleId from above
using(var session = sessionFactoy.OpenSession())
{
using(var tx = session.BeginTransaction())
{
Sample sample = session.Get<Sample>(sampleId);
Assert.That(sampleId, Is.GreaterThan(0));
Assert.False(sample.IsTransient)
session.Delete(sample);
tx.Commit();
}
}
Assert.That(sample.Id, Is.EqualTo(0));
Assert.True(sample.IsTransient)
With 'use_identifier_rollback
' nhibernate sets the id to '0' or more exactly to the default of the identity. My IsTransient
property depends on Id == 0
- How do you handle entities when they becomes deleted, in case of is the entity transient or what is the Id of a deleted entity, ...?