NHibernate - define where condition
In my application the user can defines search-conditions. He can choose a column, set an operator (equals, like, greater than, less or equal than, etc.) and give in the value. After the user clicks on a button and the application should do a search on the database with the condition. I use NHibernate and ask me now, what is the efficientest way to do this with NHibernate.
Should I create a query with it like (Column=Name, Operator=Like, Value=%John%)
var a = session.CreateCriteria<Customer>();
a.Add(Restrictions.Like("Name", "%John%"));
return a.List<Customer>();
Or should I do this with HQL:
var q = session.CreateQuery("from Customer where " + where);
return q.List开发者_运维技巧<Customer >();
Or is there a more bether solution?
Thanks for your help.
Best Regards, Thomas
You can use either one of them. There might be hardly an differences between the two. But whatever you do make sure that your column names are in constants or are mapped to the column name otherwise your repository will be tightly coupled to your model definition i.e if you update the columnname you will have to go and update these statements yourself.
And when you are building the where clause makes ure you have a function that appends the right query. you will probably be having a switch case statement for the same.
In term of efficence there is no difference. In the HQL version I would prefer use a parameter instead of adding the where part as a string. If you are using NH3.0 you can consider using QueryOver too, to avoid using string to describe your properties
精彩评论