I have a stored procedure in my database that calculates the distance between two lat/long pairs. This stored procedure is called “DistanceBetween”. I have a SQL statement allows a user to search for all items in the Items table ordered by the distance to a supplied lat/long coordinate. The SQL statement is as follows:
SELECT Items.*, dbo.DistanceBetween(@lat1, @lat2, Latitude, Longitude) AS Distance
FROM Items
ORDER BY Distance
How do I go about using this query in NHibernate? The Item class in my domain doesn’t have a “Distance” property since there isn’t a “Distance” column in my Items table. The “Distance” property really only comes into play when the user is performing this search.
There are basically three approaches that can be used, some of which have already been discussed:
CreateCriteria/ICriteriaquery; downsides: it is not part of the entities/DAL; upsides: it is flexible;formula; downsides: it is not always feasible or possible, performance can degrade if not careful; upsides: it the calculation an integral part of your entities;I’ll briefly show an example of option 2 and 3 here, I believe option 1 has been sufficiently covered by others earlier in this thread.
Option two, as in this example, is particularly useful when the query can be created as a subquery of a select statement and when all needed parameters are available in the mapped table. It also helps if the table is not mutable and/or is cached as read-only, depending on how heavy your stored procedure is.
If the above is not possible due to restrictions in the mappings, problems with caching or if your current cache settings retrieve one by one instead of by bigger amounts and you cannot change that, you should consider an alternate approach, for instance a separate mapping of the whole query with parameters. This is quite close to the CreateSqlQuery approach above, but forces the result set to be of a certain type (and you can set each property declaratively):
You can call this query as follows:
Depending on your needs, you can choose an approach. I personally use the following rule of thumb to decide what approach to use:
formulaapproach;sql-query+ mapping approach;ICriteriaor HQL approach through code.About the ordering of the data: when you choose the “formula” or the “sql-query mapping” approach you’ll have to do the ordering when you retrieve the data. This is not different then with retrieving data through your current mappings.
Update: terrible edit-mistake corrected in the sql-query XML.