NHibernate difference between Query, Get and Load

前端 未结 2 933
遥遥无期
遥遥无期 2020-12-21 09:57

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          


        
2条回答
  •  礼貌的吻别
    2020-12-21 10:37

    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:

    • Different between session.get() and session.load()
    • NHibernate – The difference between Get, Load and querying by id

提交回复
热议问题