Override delete behavior in NHibernate

In my application, users cannot truly delete entries. Rather, the โ€œRemoteโ€ field sets the value to 1, which hides it from selection.

I need to support this behavior, and I am studying whether NHibernate is suitable for my application. Can I redefine NHibnernate's deletion behavior so that instead of issuing DELETE statements it will issue UPDATES as described above?

I also need to clearly redefine its behavior SELECT, to include a sentence < AND Deleted = 0 . Or read from the presentation. I'm not sure.

+4
source share
3 answers

I think the best way to get this behavior is to implement the IInterceptor interface, which allows you to execute your own code, as shown in the NHibernate Documentation .

Otherwise, you can simply create a delete trigger that will perform the update. This solution is simpler, but is it suitable for your needs?

As for SELECT, you just need to write a method that will use Criterion with the Where clause to indicate the thing Deleted = 0.

+2
source

To implement soft deletion, simply bypass the Hibernate removal mechanism. Instead, map the Deleted table field to a .Net boolean with the same name. To delete an item, set item.Deleted = true . Then add the where attribute to your class mapping to filter out the deleted items. If you want, create another mapping for deleted items. Otherwise, they will become invisible to your application, but perhaps this is what you want.

Edit:. Perhaps this is the best approach: use the <sql-delete> 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 combined with the where attribute will be just a ticket. For instance:

 <class name="MyClass" table="my_table" where="deleted=0"> ... <sql-delete>UPDATE my_table SET deleted=1 WHERE id=?</sql-delete> </class> 
+12
source

I implemented this using INSTEAD OF DELETE triggers on SQL Server to set the delete flag bit when SQL DELETE is issued. This has two advantages: 1) I can simply delete deleted files from my application. without worry and 2) It provides soft deletes for all access to the database (i.e. the trigger should be temporarily disabled for hard deletion). Then I set up the views that only active records select and map NHibernate to them. This solution worked very well for me.

+4
source

Source: https://habr.com/ru/post/1306259/


All Articles