Question

I am wondering how can one delete an entity having just its ID and type (as in mapping) using NHibernate 2.1?

Was it helpful?

Solution

If you are using lazy loading, Load only creates a proxy.

session.Delete(session.Load(type, id));

With NH 2.1 you can use HQL. Not sure how it actually looks like, but something like this: note that this is subject to SQL injection - if possible use parametrized queries instead with SetParameter()

session.Delete(string.Format("from {0} where id = {1}", type, id));

Edit:

For Load, you don't need to know the name of the Id column.

If you need to know it, you can get it by the NH metadata:

sessionFactory.GetClassMetadata(type).IdentifierPropertyName

Another edit.

session.Delete() is instantiating the entity

When using session.Delete(), NH loads the entity anyway. At the beginning I didn't like it. Then I realized the advantages. If the entity is part of a complex structure using inheritance, collections or "any"-references, it is actually more efficient.

For instance, if class A and B both inherit from Base, it doesn't try to delete data in table B when the actual entity is of type A. This wouldn't be possible without loading the actual object. This is particularly important when there are many inherited types which also consist of many additional tables each.

The same situation is given when you have a collection of Bases, which happen to be all instances of A. When loading the collection in memory, NH knows that it doesn't need to remove any B-stuff.

If the entity A has a collection of Bs, which contains Cs (and so on), it doesn't try to delete any Cs when the collection of Bs is empty. This is only possible when reading the collection. This is particularly important when C is complex of its own, aggregating even more tables and so on.

The more complex and dynamic the structure is, the more efficient is it to load actual data instead of "blindly" deleting it.

HQL Deletes have pitfalls

HQL deletes to not load data to memory. But HQL-deletes aren't that smart. They basically translate the entity name to the corresponding table name and remove that from the database. Additionally, it deletes some aggregated collection data.

In simple structures, this may work well and efficient. In complex structures, not everything is deleted, leading to constraint violations or "database memory leaks".

Conclusion

I also tried to optimize deletion with NH. I gave up in most of the cases, because NH is still smarter, it "just works" and is usually fast enough. One of the most complex deletion algorithms I wrote is analyzing NH mapping definitions and building delete statements from that. And - no surprise - it is not possible without reading data from the database before deleting. (I just reduced it to only load primary keys.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top