Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override delete behaviour in NHibernate

In my application users cannot truly delete records. Rather, the record's Deleted field gets set to 1, which hides it from selects.

I need to maintain this behaviour and I'm looking into whether NHibernate is appropriate for my app. Can I override NHibnernate's delete behaviour so that instead of issuing DELETE statements, it issues UPDATES, as described above?

I would obviously also need to override its SELECT behaviour to include the 'AND Deleted = 0' clause. Or read from a view instead. I'm not sure.

like image 618
David Avatar asked Dec 02 '22 05:12

David


1 Answers

To implement a soft delete just bypass the Hibernate delete mechanism. Instead, map your table's Deleted field to a .Net boolean property by the same name. To delete an item, set item.Deleted = true. Then add a where attribute to your class mapping to filter out the deleted items. If you like, create another mapping for deleted items. Otherwise they will become invisible to your application, but maybe that's what you want.

Edit: Here is perhaps a better approach: use the <sql-delete> tag to write a custom delete operation for your mapping. See http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querysql.html#querysql-cud. I think this in combo with the where attribute would be just the ticket. For example:

<class name="MyClass" table="my_table" where="deleted=0">
  ...
  <sql-delete>UPDATE my_table SET deleted=1 WHERE id=?</sql-delete>
</class>
like image 181
nw. Avatar answered Dec 11 '22 16:12

nw.