Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if a referenced object can be deleted?

I have an object called "Customer" which will be used in the other tables as foreign keys.

The problem is that I want to know if a "Customer" can be deleted (ie, it is not being referenced in any other tables).

Is this possible with Nhibernate?

like image 656
Jey Geethan Avatar asked Feb 19 '10 07:02

Jey Geethan


1 Answers

What you are asking is to find the existence of the Customer PK value in the referenced tables FK column. There are many ways you can go about this:

  1. as kgiannakakis noted, try to do the delete and if an exception is thrown rollback. Effective but ugly and not useful. This also requires that you have set a CASCADE="RESTRICT" in your database. This solution has the drawback that you have to try to delete the object to find out that you can't

  2. Map the entities that reference Customer as collections and then for each collection if their Count > 0 then do not allow the delete. This is good because this is safe against schema changes as long as the mapping is complete. It is also a bad solution because additional selects will have to be made.

  3. Have a method that performs a query like bool IsReferenced(Customer cust). Good because you can have a single query which you will use when you want. Not so good because it may be susceptible to errors due to schema and/or domain changes (depending on the type of query you will do: sql/hql/criteria).

  4. A computed property on the class it self with a mapping element like <property name="IsReferenced" type="long" formula="sql-query that sums the Customer id usage in the referenced tables" />. Good because its a fast solution (at least as fast as your DB is), no additional queries. Not so good because it is susceptible to schema changes so when you change your DB you mustn't forget to update this query.

  5. crazy solution: create a schema bound view that makes the calculation. Make the query on it when you want. Good because its schema-bound and is less susceptible to schema changes, good because the query is quick, not-so-good because you still have to do an additional query (or you map this view's result on solution 4.)

2,3,4 are also good because you can also project this behavior to your UI (don't allow the delete)

Personally i would go for 4,3,5 with that preference

like image 72
Jaguar Avatar answered Oct 06 '22 17:10

Jaguar