I\'d like to find the difference in using these three ways of getting data from the database when doing something like:
public T GetById(int id) {
using
Similar try to explain it is here
In general we've got three ways how to get an instance from DB by its ID.
1) Querying - That is where we use QueryOver API (native NHibernate language) or Query (implementation of the MS LINQ API). These queries always hit the DB (or cache) and could load full root object, fetch some relations, or be just projections (only few columns/properties converted into some DTO)
2) Then, we have Get
, which was intended as the most common way how to get item by ID. It always hits DB because its contract says (get):
Return the persistent instance of the given entity class with the given identifier, or null if there is no such persistent instance
So, to be sure that object exists or not, DB must be hit.
3) Finally, there is a third contract - Load
. It will never hit DB to check if there is such an item (with provided ID): load():
Return the persistent instance of the given entity class with the given identifier, assuming that the instance exists.
If we've got a reference ID, and we know that it does exist we should use the Load
.
It will just create a proxy - with provided ID and during the INSERT or UPDATE of that root/holder entity, the proxy ID will be used to create correct SQL Statement.
Summary: Get()
and Load()
are there for us for a reason. They were designed to support different scenarios.
See also: